vue 根据登录角色显示不同的菜单栏,登录成功后使用路由守卫做重定向。
上代码:
RouterModel.beforeEach((to, from, next) => {
let user = JSON.parse(localStorage.getItem("user.info.more.1"));
function roleHanel() {
let roleId = (user.role || {}).id || 0;
console.log(roleId);
// 避免陷入死循环
if (to.path == "/components/LeftMenu") {
if (roleId == 1) {
next({ path: "/dataStatistics" });
} else {
next({ path: "/workOrderManager" });
}
} else {
next();
}
}
if (user != null) { // 已登录
if (to.path == "/") {
next({ path: "/components/LeftMenu" });
} else {
roleHanel()
}
} else { // 未登录
if (to.path != "/" && ["/register","/resetPassword"].indexOf(to.path) == -1) {
next({ path: "/" });
} else {
next();
}
}
// console.log("user = ", user);
// console.log("to = ", to);
// console.log("from = ", from);
})
自认为写得没有问题,一运行就控制台就报错。

核心报错如下:
Uncaught (in promise) Error: Redirected when going from "/" to "/components/LeftMenu" via a navigation guard.
刚上搜了半小时,各种说法都有,什么rotuer版本不对,如何解决死循环等待,都不对,意思是有个异常,其实这是我们需要的。
为了不让这个地方显示,在登录成功跳转的时候添加catch方法即可。
上代码:
that.$router.replace("/components/LeftMenu").catch((error) => {
console.log(" error", error);
});
这个打印的内容和报红的内容是一个,注释掉这个输出即可。
网友评论