Vuex刷新页面数据消失问题解决【Vue多页面跳转数据消失】

旧城等待, 2022-02-19 03:07 1374阅读 0赞

问题说明:登陆成功后,后台返回token我设置到Vuex中去了,但是跳转到主页的时候token没了

如果你还不知道怎么设置vue多页面共用Vuex看这里Vue多页面共用一个Vuex

我的跳转是用window.location.href,我也不知道为什么我的$router.push无法成功跳转

window.location.href跳转会导致你的页面刷新,从而丢失Vuex的数据

如果你是单页面刷新导致Vuex数据丢失,只需要把下面的代码复制到App.vue里面就好了
  1. created(){ //在页面加载时读取localStorage里的状态信息
  2. localStorage.getItem("userMsg") && this.$store.replaceState(Object.assign(this.$store.state,JSON.parse(localStorage.getItem("userMsg"))));
  3. //在页面刷新时将vuex里的信息保存到localStorage里
  4. window.addEventListener("beforeunload",()=>{
  5. localStorage.setItem("userMsg",JSON.stringify(this.$store.state))
  6. })
  7. },

在这里插入图片描述

如果你是多页面(比如我这个登陆页面和主页面)只需要把上面的代码再copy一份到login.vue就好了

在这里插入图片描述

如果你是在使用nuxt的时候遇到了这个问题,看这里 : https://blog.csdn.net/Tomwildboar/article/details/97616705

发表评论

表情:
评论列表 (有 0 条评论,1374人围观)

还没有评论,来说两句吧...

相关阅读