nuxt vue中刷新vuex state 数据丢失解决方案
nuxt
1 配置插件(),太简单就不说了。
注意:要禁止服务端运行,不然会报错,这个事件是在客户端添加的,不是在服务端小渲染的时候添加的。
2 写代码,如下。
export default function(ctx){
// 离开页面
window.addEventListener('beforeunload', ()=> {
console.log('触发离开事件')
sessionStorage.setItem("store",JSON.stringify(ctx.store.state))
});
// 页面加载完成
window.addEventListener('load', ()=> {
console.log('触发加载完成事件')
let storeCache = sessionStorage.getItem("store")
if(storeCache != null&&storeCache != undefined&& storeCache!= ''){
// 普通的state属性高更改的话需要用mutations ,但是如果你修改的是state 根属性的时候,那么
// 就要使用replaceState 方法了。
ctx.store.replaceState(JSON.parse(storeCache));
}
});
}
vue
vue 就更简单了,直接在main.js
的入口文件添加代码就可以了。