在做一個登陸功能的時候遇到的一個小問題。需求是用戶沒有登錄的時候打開其他頁面都是跳轉到登錄頁面,登陸之后則可以正常使用。查vue-router的文檔,發現使用beforeEach可以實現功能,于是嘗試著寫了一下:
router.beforeEach((to, from, next) => {
// 模擬登陸狀態
let isLogin = false;
if (!isLogin) {
next({path: '/login'});
}else {
next();
}
});
發現報錯:
報錯
大概意思是溢出了,也就是說每次到next又會再次進入beforeEach,所以進入了死循環。
改造如下:
router.beforeEach((to, from, next) => {
// 模擬登陸狀態
let isLogin = false;
if (!isLogin) {
if (to.path !== '/login') {
return next({path: '/login'});
}else {
next();
}
}else {
if (to.path === '/login') {
return next({path: '/'});
}
next();
}
});
然后就正常了~