目录数据丢失的原因方法1:使用第三方库 Vuex-persistedstate01 store / index.js 之 localStorage02 store / index.j
vuex存储的数据只是在页面中,相当于全局变量,页面刷新的时候vuex里的数据会重新初始化,导致数据丢失。
因为vuex里的数据是保存在运行内存中的,当页面刷新时,页面会重新加载vue实例,vuex里面的数据就会被重新赋值。
npm install --save vuex-persistedstate
- 注意点: vuex-persistedstate默认存储在 localStorage之中,基本上不需要配置什么
import createPersistedState from "vuex-persistedstate"
const store =newVuex.Store({
state: {
cartList: [],
},
mutations: {},
actions: {},
// 当state中的值发生改变,此时localStorage中的vuex的值会同步把state中的所有值存储起来,当页面刷
新的时候,state的值会从localStorage自动获取vuex的value值,赋值到state中
plugins: [createPersistedState()]
})
import createPersistedState from "vuex-persistedstate"
const store = new Vuex.Store({
state: {},
mutations: {},
actions: {},
plugins: [createPersistedState({
storage:window.sessionStorage // 同localStorage相同,只是将vuex的所有值存储到sessionStorage中
})]
})
import createPersistedState from "vuex-persistedstate"
const store = newVuex.Store({
state: {
count: 0
},
mutations: {},
actions: {},
plugins: [createPersistedState({
storage:window.sessionStorage,
reducer(val) {
// 此时,当count发生改变的时候,就会调用此函数,并且val的值为当前state对象,return的值为当前本地存储的value值(本地存储的key值为vuex)
return {
count: val.count,
changeCount: 'aaa'
}
}
})]
})
store / index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
orderList: [],
menuList: []
},
mutations: {
orderList(s, d) {
s.orderList= d;
window.localStorage.setItem("list",JSON.stringify(s.orderList))
},
menuList(s, d) {
s.menuList = d;
window.localStorage.setItem("list",jsON.stringify(s.menuList))
},
}
})
页面刷新的时候
通过监听beforeunload事件来进行数据的localStorage存储,beforeunload事件在页面刷新时进行触发,具体做法是在App.vue的created()周期函数中下如下代码
if (window.localStorage.getItem("list") ) {
this.$store.replaceState(Object.assign({}, this.$store.state,JSON.parse(window.localStorage.getItem("list"))))
}
window.addEventListener("beforeunload",()=>{
window.localStorage.setItem("list",JSON.stringify(this.$store.state))
})
到此这篇关于解决vuex数据丢失问题的文章就介绍到这了,更多相关vuex 数据丢失内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: 解决vuex数据丢失问题
本文链接: https://www.lsjlt.com/news/193908.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0