最近写vue2 项目需要用到vuex, 但遇到一个问题,存进store里的数据刷新就丢失了,于是乎百度解决。将自己的感受与解决方法记录下来。
数据丢失的原因
vuex存储的数据只是在页面中,相当于全局变量,页面刷新的时候vuex里的数据会重新初始化,导致数据丢失。
因为vuex里的数据是保存在运行内存中的,当页面刷新时,页面会重新加载vue实例,vuex里面的数据就会被重新赋值。
解决的思路
将vuex中的数据直接保存到浏览器缓存中(sessionStorage、localStorage、cookie) 页面刷新后再从浏览器中取出
解决方法
利用第三方库进行持久化存储
1.安装 vuex-persistedstate
npm install --save vuex-persistedstate
2.根据情况选择存储位置和方法
(1)在store文件夹下的indedx.js中配置信息,
使用vuex-persistedstate默认存储到localStorage
使用vuex-persistedstate默认存储到localStorage
import createPersistedState from "vuex-persistedstate"
const store =newVuex.Store({
state: {
count: 1
},
mutations: {},
actions: {},
// 当state中的值发生改变,此时localStorage中的vuex的值会同步把state中的所有值存储起来,当页面刷
新的时候,state的值会从localStorage自动获取vuex的value值,赋值到state中
plugins: [createPersistedState()]
})
(2)使用vuex-persistedstate默认存储到sessionStorage
const store = new Vuex.Store({
state: {},
mutations: {},
actions: {},
plugins: [createPersistedState({
storage:window.sessionStorage // 同localStorage相同,只是将vuex的所有值存储到sessionStorage中
})]
})
(3)指定需要持久化的state
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'
}
}
})]
})
参考文章:解决Vuex刷新页面数据丢失的问题
下班~