使用Vue-Router的导航守卫-无限循环问题
我在项目里面用到了的是全局守卫,beforeEach,方便管理
不过遇到了一个问题,就是在beforeEach()中设置好判断条件后出现了无限循环的问题
当时的代码如下:
router.beforeEach((to, from, next) => {
if (isLogin) {
next()
} else {
console.log('测试')
next('login')
}
})
这个问题我是这样理解的:
next() 表示路由成功,直接进入to路由,不会再次调用router.beforeEach()
next(‘login’) 表示路由拦截成功,重定向至login,会再次调用router.beforeEach()
也就是说beforeEach()必须调用next(),否则就会出现无限循环,next() 和 next(‘xxx’) 是不一样的,区别就是前者不会再次调用router.beforeEach(),后者会!!!
最终解决的代码如下:
router.beforeEach((to, from, next) => {
if (isLogin) {
next()
} else {
if (to.name === 'login') {
next()
} else {
console.log('测试')
next('login')
}
}
})
热门推荐
10 高一祝福语简短 励志
11 立秋节气简短祝福语
12 简短公司周年祝福语大全
13 中考感言简短祝福语大全
14 体育老师简短祝福语
15 干杯生日祝福语简短独特
16 特别简短的祝福语老师
17 朋友坐车走了祝福语简短
18 给英雄的祝福语简短