【问题标题】:Vue-Router infinite loop with redirect route带有重定向路由的Vue-Router无限循环
【发布时间】:2019-12-30 18:12:03
【问题描述】:

我正在尝试找到将未经身份验证的用户重定向到登录页面/屏幕的最佳方法。目前,我正在尝试在加载组件之前在路由中使用 JWT 令牌进行身份验证。但是,我在router.beforEach() 上遇到了无限循环:

router.beforeEach((to, from, next) => {
  if (to.matched.some(r => r.meta.requiresAuth)) {
    alert('needs auth!'); // used for testing
    if (localStorage.getItem('jwt') == null) {
      next('/login'); // here is where the infinite loop hits
    } else {
      next();
    }
  } else {
    next();
  }
});

当我到达需要验证的路由时,next('/login') 调用会陷入无限循环。我可以这样避免:

if (to.path !== '/login') {
    next('/login');
} else {
    next();
  }

但这会两次调用警报,似乎是一种低效和/或笨拙的方法。有没有比这更好的方法来测试路线的条件?感谢您提供任何提示、建议、帮助

【问题讨论】:

标签: javascript vue.js vuejs2 vue-router infinite-loop


【解决方案1】:

我不认为这是 hacky。

if (to.path !== '/login') {
    next('/login');
}

当你改变路线时,它自然会再次触发router.beforeEach

您可以将其移至 if (to.matched.some(r => r.meta.requiresAuth)) { 上方以避免不必要地进行检查

if (to.path === '/login') {
    next();
}

另一种方法是跳出SPAwindow.location,但我认为这不是更好。

【讨论】:

    猜你喜欢
    • 2020-12-31
    • 2014-12-24
    • 1970-01-01
    • 2017-08-26
    • 2019-06-17
    • 2020-10-08
    • 2017-07-07
    • 2021-07-25
    • 2020-09-30
    相关资源
    最近更新 更多