首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >带导航保护的Vuex autologin

带导航保护的Vuex autologin
EN

Stack Overflow用户
提问于 2020-10-11 22:51:59
回答 1查看 180关注 0票数 0

嗨,我正在使用vue和vuex,试图设置导航路线,以便用户在令牌仍在本地存储中的情况下自动登录。我得到了一个罕见的行为,如果我检查一个getter的值,这个getter返回一个名为isauthenticated的变量,如果有一个有效的令牌,它是真的,我可以清楚地看到这个值是真的,但是当我自己获取这个值时,它会说它是假的。

代码语言:javascript
复制
router.beforeEach(function (to, from, next) {
  console.log(to);
  console.log(from);
  console.log(store.getters);
  console.log("is auth "+store.getters["auth/isAuthenticated"])
  if (to.meta.requiresAuth && !store.getters["auth/isAuthenticated"]) {
    console.log("redirected to landing page")
    next('/');
  } else if (to.meta.requiresUnauth && store.getters["auth/isAuthenticated"]) {
    console.log("redirected to home");
    console.log(to.meta.requiresUnauth);
    next('/home');
  } else {
    console.log("nexting")
    next();
  }
});

output:
{}
auth/isAuthenticated: true
auth/token: "eyJhbGciOiJSUz...."
auth/userId: "nHSQ3...."
user/username: ""
get auth/isAuthenticated: ƒ ()
get auth/token: ƒ ()
get auth/userId: ƒ ()
get user/username: ƒ ()
__proto__: Object

is auth false
nexting
EN

回答 1

Stack Overflow用户

发布于 2020-10-11 23:57:15

问题是在我的app.vue中的created()钩子运行之前的导航,我通过这样做解决了它:

代码语言:javascript
复制
store.dispatch('auth/tryLogin').then(
  router.beforeEach(function (to, from, next) {
    if (to.meta.requiresAuth && !store.getters["auth/isAuthenticated"]) {
      console.log("redirected to landing page")
      next('/');
    } else if (to.meta.requiresUnauth && store.getters["auth/isAuthenticated"]) {
      console.log("redirected to home");
      next('/home');
    } else {
      console.log("nexting")
      next();
    }
  }));

你可以在这里阅读更多信息Router beforeEach guard executed before state loaded in Vue created()

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64305381

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档