}
}
} else {
/* has no token*/
if (whiteList.indexOf(to.path) !== -1) {
next()
} else {
next(/login?redirect=${to.path}
)
NProgress.done()
}
}
## 问题一:路由守卫死循环
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210301143610569.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80Mzk5MzA2NQ==,size_16,color_FFFFFF,t_70)
>
> 如图,按上面配置动态路由后,在进入路由守卫时,不断循环,无法正常转发
>
>
>
其实在路由守卫中,只有`next()`是放行,其他的诸如:`next('/logon') 、 next(to) 或者 next({ ...to, replace: true })`都不是放行,而是:**中断当前导航,执行新的导航**
例如现在我有一个守卫,在守卫中我使用`next('/logon')`,肯定有同学认为是会直接跳转到/logon路由:
beforeEach((to, from, next) => {
next(‘/logon’)
}
其实他是这么执行的:
beforeEach((to, from, next) => {
beforeEach((‘/logon’, from, next) => {
beforeEach((‘/logon’, from, next) => {
beforeEach((‘/logon’, from, next) => {
beforeEac… // 一直循环下去… , 因为我们没有使用 next() 放行
}
}
}
}
`next('/logon')`不是说直接去`/logon`路由,而是中断这一次路由守卫的操作,又进入一次路由守卫,就像嵌套一样,一层路由守卫,然后又是一层路由守卫,此时路由守卫进入到第二层时,`to.path`已经不是`/home`了,这个时候才执行`next()`放行操作。
如果守卫中没有正确的放行出口的话,会一直`next({ ...to})`进入死循环 !!!
因此你还需要确保在当`addRoutes()`已经完成时,所执行到的这一次`beforeEach((to, from, next)`中有一个正确的`next()`方向出口。
**因此想实现动态添加路由的操作的话,代码应该是这样的:**
const hasToken = getToken()[‘Authorization’]
if (hasToken) {
if (to.path === ‘/login’) {
next({ path: ‘/’ })
NProgress.done()
} else {
const hasRoles = store.getters.roles && store.getters.roles.length > 0
if(hasRoles){
next()
}else{