Vuejs 路由器和 beforeEach 钩子

Vuejs router and beforeEach hook

我遇到了 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) 之前,就像我在网上看到的那样,但它没有解决任何问题。 我可以通过在每条路线上使用 beforeEnter() 来修复它,但我想使用全局解决方案,而不必在每条路线上增加代码。

你能帮帮我吗?

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).