在 vue-router
中使用addRoutes
添加动态路由无效.
import Vue from 'vue'
import Router from 'vue-router'
import Layout from '@/views/layout'
const _import = comp => require(`@/views/${comp}`).default
Vue.use(Router)
//全局静态路由
const constantRouters = [
{ path: '/login', name: 'login', component: _import('commons/login/login'), hidden: true },
{ path: '/error', name: 'error', component: _import('commons/errorPage'), hidden: true }
]
//全局路由守卫
router.beforeEach((to, from, next) => {
let token = getToken()
//已登录
if (token && token.length > 0) {
//如果没有获取 用户信息
if (store.getters.user.length < 1) {
//这里没有使用 接口中的数据. 使用数据模拟.
let mainRoutes = [{
path: '/',
component: Layout,
name: 'layout',
redirect: '/home',
children: [
{ path: '/home', component: _import('modules/home'), name: 'home', meta: { title: '首页' } }
],
// 主路由守卫
beforeEnter (to, from, next) {
let token = getToken()
if (! token) {
next({ path: '/login' })
} else {
next()
}
}
}]
router.addRoutes(mainRoutes)
// next({ ...to, replace: true })
}
next()
} else {
//否则直接进入 登录页
next({ path: '/login' })
}
})
const router = new Router({
routes: constantRouters
})
export default router
访问 http://localhost:8080/#/ 会跳转到 http://localhost:8080/#/login 页面也是正常显示.
登录成功后 router.push('/')
到根路径 页面是一篇空白.
确定路径这些都没有问题.组件都是正常加载到.我实在不知道我错在哪里...
beforeEach中使用addRoutes是无法添加的,因为这是访问路由之前的钩子,你需要自己做判断,addRoutes过后重定向到访问的页面,再次访问就可以了,因为已经执行过addRoutes了