我在项目里面用到了的是全局守卫,beforeEach,方便管理不过遇到了一个问题,就是在beforeEach()中设置好判断条件后出现了无限循环的问题当时的代码以下:chrome
router.beforeEach((to, from, next) => {
if (isLogin) {
next()
} else {
console.log('测试')
next('login')
}
})复制代码
结果chrome的debug中看到:markdown
这个问题我是这样理解的:next() 表示路由成功,直接进入to路由,不会再次调用router.beforeEach()next('login') 表示路由拦截成功,重定向至login,会再次调用router.beforeEach()也就是说beforeEach()必须调用next(),不然就会出现无限循环,next() 和 next('xxx') 是不同的,区别就是前者不会再次调用router.beforeEach(),后者会!!!官网这样写的(主要是红线标记的那句!):测试
最终解决的代码以下:spa
router.beforeEach((to, from, next) => {
if (isLogin) {
next()
} else {
if (to.name === 'login') {
next()
} else {
console.log('测试')
next('login')
}
}
})复制代码