利用全局前置守卫来进行路由控制,判断是否登录,没登录去登录页,登陆了就判断是否添加了路由列表,然后继续跳转
如下代码,写完后会发现,页面空白,并会进入死循环
router.beforeEach(async(to, from, next) => {
const name = storage.session.get('username')
if (name) {
// 已经登录
if (store.getters.realRouter.length === 0) {
const realRoutes = await store.dispatch('combine/combinRoutes')
router.addRoutes(realRoutes)
next({ ...to, replace: true })
} else {
next()
}
} else {
// 未登录
next({
path: '/login'
})
}
}
原因在于未登录,去跳转'/login'页,又会触发router.beforeEach,又会去跳转'/login'页,所以要下面这样写来防止循环
router.beforeEach(async(to, from, next) => {
const name = storage.session.get('username')
if (name) {
已经登录
if (store.getters.realRouter.length === 0) {
const realRoutes = await store.dispatch('combine/combinRoutes')
router.addRoutes(realRoutes)
next({ ...to, replace: true })
} else {
next()
}
} else {
// 未登录
if (to.path === '/login') {
// 如果是去登录页,直接next
next()
} else {
next({
path: '/login'
})
}
}
}