【问题标题】:Vuejs router and beforeEach hookVuejs 路由器和 beforeEach 钩子
【发布时间】:2019-08-11 06:33:54
【问题描述】:

我遇到了 vue-router 的 beforeEach 钩子的问题:我在 main.js 中使用 router.beforeEach 钩子检查了用户的身份验证,如下所示:

router.beforeEach((to, from, next) => {
  if (to.name !== 'Login' && to.name !== 'PasswordReset' && to.name !== 'ForgetPass' && to.name !== 'SsoLogin') {
    Auth.isLogged()
      .then(() => {
        next();
      })
      .catch(() => {
        next(`/login?redirectUrl=${to.fullPath}`);
      });
  }
  next();
});

问题是网页在重定向发生之前显示了 1 秒。 我尝试将上面的代码放在 Vue.use(Router) 之前,就像我在 Internet 上看到的那样,但它没有解决任何问题。 我可以通过在每条路线上使用 beforeEnter() 来修复它,但我想使用全局解决方案,而不是在每条路线上乘以代码。

你能帮帮我吗?

【问题讨论】:

    标签: vuejs2 vue-router


    【解决方案1】:
    router.beforeEach((to, from, next) => {
      if(...) {
        Auth.isLogged().then().catch();
      } else {
        next()
      }
    }
    

    您需要添加 else,因为 Auth.isLogged() 是异步的。如果不添加 else,最后的 next() 将始终被执行。所以,你会先看到页面(last next() been executed),然后页面重定向(code in then() or catch() block been executed)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-14
      • 2022-01-18
      • 1970-01-01
      • 2020-08-18
      相关资源
      最近更新 更多