为什么会出现"Redirected when going from "/登录" to "/" via a navigation guard."?



在这里,路由器保护在我的vue应用程序上工作得很好,但在登录后,控制台上出现了以下错误:

Uncaught (in promise) Error:从"/login"/";

这是我的代码片段。

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"),
},
],
},
];

The Auth guard:

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次,因为您有两个单独的if语句,并且都将运行。

  • //路径更改为/
  • 调用nextreturn 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();
});

你可以在nuext .config.js的auth属性中添加home属性为false文件

redirect: {
login: '/login',
logout: '/login',
callback: false,
home: false
}

,然后将登录重定向到/

async login() {
try {
await this.$auth.loginWith('local', { data: this.form })
this.$router.push('/')
} catch {
...
}
}

相关内容

最新更新