最近在使用vue-router的beforeEach钩子时候遇到了一个问题,就是在beforeEach()中设置好判断条件后出现了无限循环的问题
代码如下:
// isLogined 用来判断用户是否已登录 router.beforeEach((to, from, next) => { if(isLogined){ next() }else{ console.log('测试') next('login') } })
结果chrome的debug中看到:
这个问题我是这样理解的:
router.beforeEach((to, from, next) => { if(true){ next() }else{ next('login') } })
- next() 表示路由成功,直接进入to路由,不会再次调用router.beforeEach()
- next('login') 表示路由拦截成功,重定向至login,会再次调用router.beforeEach()
也就是说beforeEach()必须调用next(),否则就会出现无限循环,
next() 和 next('xxx') 是不一样的,区别就是前者不会再次调用router.beforeEach(),后者会!!!
官网这样写的(主要是红线标记的那句!):
就上面的例子,next('login')
和 判断条件isLogin
就是一个无限死循环,只需要给 login 路由放行就可以解决问题了,在开始加一条判断if (to.name === 'login' && !isLogin){next()}
,这样就可以解决问题了。