vue.js - 刷新页面后vuex从sessionStorage获取,为什么router.beforeEach中state的为空?
本文介绍了vue.js - 刷新页面后vuex从sessionStorage获取,为什么router.beforeEach中state的为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
vuex:
const state = {
state: {
token: sessionStorage.getItem('token') || '',
},
}
router:
router.beforeEach(function(to, from, next) {
console.log(to.meta.auth,store.state.token,to.path);
if (to.meta.auth && !store.state.token && to.path !== '/login') {
return next({
path: '/login',
query: {redirect: to.fullPath}
})
}
next();
});
在用户登陆后刷新页面,为什么beforeEach里store.state.token
为空?
因为我把store写成了state...
QAQ每天都在问傻逼问题
解决方案
const store = { // 这里是 store ?
state: {
token: sessionStorage.getItem('token') || '',
},
}
初始化 store 实例时,如果没登录 token 应该是空的,之后如果登录,sessionStorage 保存到 token 后,state.token 也不会再改变了,因为没有 mutation 去触发重新获取
这篇关于vue.js - 刷新页面后vuex从sessionStorage获取,为什么router.beforeEach中state的为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文