网络编程
位置:首页>> 网络编程>> JavaScript>> 关于vuex状态刷新网页时数据被清空问题及解决

关于vuex状态刷新网页时数据被清空问题及解决

作者:不过期的约定  发布时间:2024-04-30 10:22:18 

标签:vuex,刷新网页,数据,清空

vuex状态刷新网页时数据被清空问题

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));
});

vuex状态在页面刷新时,会清空状态的解决

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))
? ? })
? }

来源:https://blog.csdn.net/chen123789hkb/article/details/90175607

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com