嗨,我正在使用vue和vuex,试图设置导航路线,以便用户在令牌仍在本地存储中的情况下自动登录。我得到了一个罕见的行为,如果我检查一个getter的值,这个getter返回一个名为isauthenticated的变量,如果有一个有效的令牌,它是真的,我可以清楚地看到这个值是真的,但是当我自己获取这个值时,它会说它是假的。
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发布于 2020-10-11 23:57:15
问题是在我的app.vue中的created()钩子运行之前的导航,我通过这样做解决了它:
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()
https://stackoverflow.com/questions/64305381
复制相似问题