我在專案里面用到了的是全域守衛,beforeEach,方便管理
不過遇到了一個問題,就是在beforeEach()中設定好判斷條件后出現了無限回圈的問題
當時的代碼如下:
router.beforeEach((to, from, next) => {
if (isLogin) {
next()
} else {
console.log('測驗')
next('login')
}
})
結果chrome的debug中看到:

這個問題我是這樣理解的:
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')
}
}
})
覺得有幫助的小伙伴右上角點個贊~

掃描上方二維碼關注我的訂閱號~
覺得有幫助的小伙伴點個贊~
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/63557.html
標籤:其他
