How to guard both '/login' or '/login/', and '/dashboard' or '/dashboard/' in vue-router

跟風遠走 提交于 2021-01-29 13:16:44

问题


I'm using vue-router to set routeguard in my system, redirecting the user if there's a token back to dashboard if they try to input /login or /login/ in the URL, and vice versa if they have no token.

router.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();
});

my problem is that if I type '/login' or '/dashboard' (without the backslash in the end), it bypasses my guard, so I tried doing (to.fullPath === '/login/' || '/login') and (to.fullPath === '/dashboard/' || '/dashboard') in my code, which was a success literally 4 hours ago.

Then I returned now and it's now giving me errors, saying [vue-router] uncaught error during route navigation whenever I change views via URL.

I have no idea why it stopped working, please help.

Thank you!

EDIT: I made a typo and was calling accessToken instead of authToken that's why the guard failed. Fixed, thank you!


回答1:


You could give your routes a name and redirect based on that instead.

An extra change could be to add some meta to your routes whether the route requires the user to be authenticated, making it easier to scale without having to specify each protected route in your beforeEach

routes

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

guard

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();
});



回答2:


Just use startsWith instead of === for comparison:

if (to.fullPath.startsWith('/dashboard') {...

This way you're not concerned with the trailing slashes, etc.



来源:https://stackoverflow.com/questions/58400151/how-to-guard-both-login-or-login-and-dashboard-or-dashboard-in-vu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!