当我们刷新页面时,vue 实例会被重新加载, vuex 仓库里的数据也会被初始化,这会导致数据的丢失。
解决方法:
我们可以在页面将要刷新之前将 state 中的数据保存到 sessionStorage 中,待页面刷新之后再将数据取出,重新赋值给 state,然后清空 sessionStorage。
在根组件 App.vue 中添加如下代码:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 
 | setup() {const store = useStore();
 
 const data = sessionStorage.getItem("store");
 if (data) {
 store.replaceState(
 Object.assign(
 store.state,
 JSON.parse(data)
 )
 );
 sessionStorage.removeItem("store");
 }
 
 window.addEventListener("beforeunload", () => {
 sessionStorage.setItem("store", JSON.stringify(store.state));
 });
 }
 
 | 
其中,
| 1
 | Object.assign(target, sources)
 | 
方法可以将 sources 对象中的属性和值分配到 target 对象中。