首页 > 解决方案 > 如何在 vue-router 中同时保护 '/login' 或 '/login/' 和 '/dashboard' 或 '/dashboard/'

问题描述

我正在使用 vue-router 在我的系统中设置路由保护,如果用户尝试在 URL 中输入 /login 或 /login/ 则将用户重定向回仪表板,反之亦然,如果他们没有令牌。

路由器.js

router.beforeEach((to, from, next) => {
  if (to.fullPath === '/dashboard/') {
    if (!store.state.authToken) {
      next('/login');
    }
  }
  if (to.fullPath === '/login/') {
    if (store.state.accessToken) {
      next('/dashboard');
    }
  }
  next();
});

我的问题是,如果我输入 '/login' 或 '/dashboard' (最后没有反斜杠),它会绕过我的防护,所以我尝试 在我的代码中进行操作(to.fullPath === '/login/' || '/login')(to.fullPath === '/dashboard/' || '/dashboard')这在 4 小时前就成功了。

然后我现在回来了,现在它给了我错误,说[vue-router] uncaught error during route navigation每当我通过 URL 更改视图时。

我不知道它为什么停止工作,请帮忙。

谢谢!

编辑:我打错了,打电话给 accessToken 而不是 authToken 这就是警卫失败的原因。已修复,谢谢!

标签: vue.jsvue-router

解决方案


您可以为您的路线命名并根据该名称进行重定向。

额外的更改可能是向您的路由添加一些元数据,无论该路由是否需要用户进行身份验证,从而使其更易于扩展,而无需在您的 beforeEach 中指定每个受保护的路由

路线

{
  path: '/login',
  name: 'login',
  component: () => import('./views/Login.vue'),
  meta: { requiresAuth: false }
},
{
  path: '/dashboard',
  name: 'dashboard',
  component: () => import('./views/Dasboard.vue'),
  meta: { requiresAuth: true }
}

警卫

router.beforeEach((to, from, next) => {
  /* Both '/login' and '/login/' should share the same route name even if their path is different */
  if (to.name === 'login') {
    if (store.state.accessToken) {
      next('/dashboard');
    }
  }

  //Redirect to login if the route requires auth and no token is set
  if(to.meta.requiresAuth) {
    if (!store.state.accessToken) {
      next('/login');
    }
  }

  next();
});

推荐阅读