Vuex页面F5被刷新后,state内容全部丢失的问题解决

问题:

页面如果被F5强制刷新了,那么store.state里的内容就会被清空。这显然不是我们所希望看到的。

结合localStorage缓存可以解决该问题。

在main.js中绑定下页面刷新事件,如果有刷新事件,则把store.state内容存入缓存。

然后在root.vue的create方法中去重新加载。具体代码如下:

1.工具代码

setObj: function (key, obj) {
    obj = JSON.stringify(obj);
    localStorage.setItem(key, obj);
  },
  getObj: function (key) {
    var obj = JSON.parse(localStorage.getItem(key));
    return obj;
  },

2.在main.js中写刷新绑定事件

window.addEventListener("beforeunload",()=>{
  console.log('refresh');
  ctool.setObj('store',store.state);
})

代码直接写在new Vue下面即可。

3.在root.vue的create方法中写恢复代码

created() {
      if(ctool.getObj('store')){
        this.$store.replaceState(Object.assign({}, this.$store.state,ctool.getObj('store')));
        ctool.setObj('store',null);
      }
}

这里为了避免出现异常错误,在恢复缓存后,置空缓存。

猜你喜欢

转载自blog.csdn.net/liangcha007/article/details/84664777