$router.addRoutes()+vuex 动态添加路由

1、store/index.js:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    isLogin: false
  },
  mutations: {
    login(state) {
      state.isLogin = true
    }
  }
})

2、views/Login.vue:

<template>
  <div>
    <h1>登录页面</h1>
    <button @click="handleClick">按钮</button>
  </div>
</template>
<script>
import { asyncRoutes } from '../router'
export default {
  methods: {
    handleClick() {
      this.$store.commit('login')
      this.$router.addRoutes(asyncRoutes) // 将asyncRoutes中的路由添加到路由表中
    }
  }
}
</script>

views/Register:

<template>
  <div>
    <h1>注册页面</h1>
  </div>
</template>

views/About.vue:

<template>
  <div>
    <h1>关于页面</h1>
  </div>
</template>

3、router.js:

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

import Login from '@/views/Login'
import Register from '@/views/Register'
import About from '@/views/About'
const routes = [
  { path: '/login', component: Login },
  { path: '/register', component: Register }
]

// 带权限的路由
export const asyncRoutes = [{ path: '/about', component: About }]

const router = new VueRouter({
  mode: 'history',
  routes
})

export default router

4、App.vue:

<template>
  <div id="app">
    <div class="router">
      <router-link tag='div' class="nav-link" to="/login">登录</router-link>
      <router-link tag='div' class="nav-link" to="/register">注册</router-link>
      <router-link tag='div' class="nav-link" to="/about" v-if="$store.state.isLogin">About</router-link>
    </div>
    <h1>动态添加路由</h1>
    <router-view></router-view>
  </div>
</template>
<style lang="less" scoped>
#app {
  text-align: center;
  .router {
    display: flex;
    justify-content: flex-end;
    width: 100%;
    height: 44px;
    background-color: #424242;
  }
  .nav-link {
    width: 100px;
    height: 100%;
    text-align: center;
    line-height: 44px;
    color: #fff;
  }
}
</style>

 

效果:about路由是权限路由,默认情况下vuex中isLogin为false,此时不展示。当进入到login页面时,点击登录按钮,触发vuex中isLogin为true,此时about路由展示。但此时进入到about中时router-view没有任何内容,需要在点击按钮的同时,将asyncRoutes中的路由(about)添加到路由表中,此时再进入到about路由便可以正常展示about组件

 

上一篇:vue 实战,快速上手


下一篇:Vue ——设置页面title标题