问题背景
路由加了全局守卫之后,报错:
分析原因
内部判断,导致路由产生了死循环
错误代码
router.beforeEach((to, from, next) => {
if (store.getters.token) {
if (to.path === '/login') {
next('/')
} else {
next()
}
} else {
next('/login')
}
})
解决方案
const whiteList = ['/login']
router.beforeEach((to, from, next) => {
if (store.getters.token) {
if (to.path === '/login') {
next('/')
} else {
next()
}
} else {
if (whiteList.indexOf(to.path) > -1) {
next()
} else {
next('/login')
}
}
})
也可以用下面这种方法
router.beforeEach((to, from, next) => {
if(Object.is(to.path,'/login')) {
next();
return
}
if (store.getters.token) {
next()
} else {
next('/login')
}
})
总结
其实这算是 vue-router 的一个机制了,当我们在router.push( {‘name’ : ‘login’} ) 时又重新进入了我们当前的这个router-beforeEach事件里,此时又进行了token的判断,还是没有token,导致又走到了router.push({name:‘login’}) 里,然后就是一直死循环。所以在判断之前,加了下面判断
if(Object.is(to.path,'/login')) {
next();
return
}
使用全局前置守卫碰到死循环的问题,浏览器就报了 Infinite redirect in navigation guard
// 错误示范
router.beforeEach((to, from, next) => {
next('/')
}
这样的代码会使路由陷入死循环,不断地重复进入 根路径 又从根路径 出来的无限循环
在实现跳转路由的时候,一定要以 next()结尾