vue中頁面跳牆處理
頁面跳牆中使用
vue-router
中的beforeEach
的死循環問題
- 問題展現
import Router from 'vue-router'
const router = new Router({
{path: '/', component: index },
{path: '/login', component: login},
{path: '/error', component: error},
{path: '*', component: error}
})
router.beforeEach((to, from, next) => {
const isLogin = sessionStorage.getItem('loginData')
if (isLogin) {
next()
} else {
next('/error')
}
})
最近在使用時,一直陷入死循環,當時的想法是如何將路由提取出來,脫離
beforeEach
的控制,之后發現不可行。上面問題再現,會出現死循環,因為/error
會在進入前 又要進入beforeEach
中 ,這樣就會一直循環下去
所以就是想如何跳出這個循環即可
router.beforeEach((to, from, next) => {
const isLogin = sessionStorage.getItem('loginData')
if (isLogin) {
next()
} else {
//next('/error')
if (to.path === '/error') { //這就是跳出循環的關鍵
next()
} else {
next('/error')
}
}
})
這樣寫,其實這個會執行兩次,第二次進來是以
/error
的路由進來的
總結
- 看文檔也需要 實踐哈