作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
router guard 在我的 vue 应用程序上运行良好,但登录后,控制台出现以下错误。
Uncaught (in promise) Error: Redirected when going from "/login" to "/" via a navigation guard.
这是我的代码片段。
const routes = [
{
path: "/login",
component: () => import("../views/Auth/Login"),
meta: { hideForAuth: true },
},
{
path: "/",
component: DashboardLayout,
meta: { requiresAuth: true },
children: [
{
path: "home",
name: "Home",
component: () => import("../views/Home"),
},
],
},
];
Auth 守卫:
const loggedIn = localStorage.getItem("auth");
router.beforeEach((to, from, next) => {
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (!loggedIn) {
next({ path: "/login" });
} else {
next();
}
} else {
next();
}
if (to.matched.some((record) => record.meta.hideForAuth)) {
if (loggedIn) {
next({ path: "//" });
} else {
next();
}
} else {
next();
}
});
无法找出问题所在。提前致谢!
最佳答案
由于 next
不会退出守卫,守卫将在每条路线上至少调用 next
2 次,因为您有 2 个单独的 if
语句,两者都将运行。
//
路径改为/
return next
一样调用 next
来退出函数,或者构造你的 if
语句,这样只有一个会运行。loggedIn
否则只会在创建路由器时计算一次这是一种方法,它也涵盖没有 meta
的路由:
router.beforeEach((to, from, next) => {
const loggedIn = localStorage.getItem("auth");
const isAuth = to.matched.some((record) => record.meta.requiresAuth);
const isHide = to.matched.some((record) => record.meta.hideForAuth);
if (isAuth && !loggedIn) {
return next({ path: "/login" });
} else if (isHide && loggedIn) {
return next({ path: "/" });
}
next();
});
关于javascript - 为什么 "Redirected when going from "/login"to "/"via a navigation guard."出现了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66010046/
我是一名优秀的程序员,十分优秀!