我在項目裏面用到了的是全局守衛,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')
}
}
})複製代碼