2022-07-28 09:07:38
vuex状态管理,在网页刷新数据被清空的解决方法。
在main.js中写入下面的代码段(亲测有效)
//刷新保存状态 if (sessionStorage.getItem("store")) {
store.replaceState(
Object.assign(
{},
store.state,
JSON.parse(sessionStorage.getItem("store"))
)
);
sessionStorage.removeItem("store")
} //监听,在页面刷新时将vuex里的信息保存到sessionStorage里 window.addEventListener("beforeunload", () => {
sessionStorage.setItem("store", JSON.stringify(store.state));
});
store写入的state在页面刷新时会被清空,这时可以用sessionStorage缓存状态。因为localStorage会永久保存数据,只有用户手动清除的时候才会清除。cookie存储内存只有4k,并且始终在同源的http请求中携带。而sessionStorage在关闭浏览器页面时就会清空。
因为状态只会在刷新页面的时候清空,所以我们只需要去app.vue里面在页面刷新之前把store保存在sessionStorage里面。在页面加载时读取sessionStorage的值
由于浏览器存储时会自动把对象转换成字符串格式,且不具备转换对象的键和值为字符串的效果,只会转换为[object,object]。因此需要先将对象转换为json字符串存储,取出时再使用JSON.parse()方法转换为json对象。
app.vue
created () {
// 在页面加载时读取sessionStorage if (sessionStorage.getItem('store')) {
this.$store.replaceState(Object.assign({}, this.$store.state, JSON.parse(sessionStorage.getItem('store'))))
}
// 在页面刷新时将store保存到sessionStorage里 window.addEventListener('beforeunload', () => {
sessionStorage.setItem('store', JSON.stringify(this.$store.state))
})
}
Copyright ©2018 陕西烽火云集信息科技有限公司 版权所有 陕ICP备18009853号-1 增值电信业务经营许可证B1.B2-20180802
烽火云集用户注册协议 法律声明及隐私权政策 致烽火云集用户的一封
法务支持:陕西兰天律师事务所