我们存储在vuex里面的数据只是放在了浏览器缓存里面,页面刷新就会丢失。
当然也可以通过vuex存储到本地,再去获取也可以实现页面刷新数据不丢失。
本篇主要讲解vuex-persistedstate这个插件,原理同上,只不过不需要去手写存储的代码,根据简单的配置就可以实现
一、下载
npm install vuex-persistedstate --save
二、使用—在store文件夹的index.js引入及配置插件
根据项目需求来,可以分模块去配置,也可以不分模块
1.不分模块
直接在stroe/index.js里面配置即可在这里插入代码片
import Vuex from "vuex";
import Vue from 'vue'
// 引入插件
import createPersistedState from "vuex-persistedstate";
Vue.use(Vuex);
const state = {
};
const mutations = {
};
const actions = {
};
const store = new Vuex.Store({
state,
mutations,
actions,
/* vuex数据持久化配置 */
plugins: [
createPersistedState({
// 存储方式:localStorage、sessionStorage、cookies
storage: window.sessionStorage,
// 存储的 key 的key值
key: "store",
render(state) {
// 要存储的数据:本项目采用es6扩展运算符的方式存储了state中所有的数据
return {
...state
};
}
})
]
});
export default store;
2.分模块
模块中这样写:
export default ({
state: {
},
mutations: {
},
actions: {
}
})
stroe/index.js里面这样配置:
import Vuex from "vuex";
import Vue from 'vue'
// 引入模块
import fanSystem from './modules/fanSystem'
// 引入插件
import createPersistedState from "vuex-persistedstate";
Vue.use(Vuex);
const getters = {
}
const store = new Vuex.Store({
// 有哪些模块
modules: {
fanSystem
},
getters,
/* vuex数据持久化配置 */
// plugins: [createPersistedState()],//没有任何参数的配置写法
plugins: [
createPersistedState({
//带参数的写法
// 存储方式:localStorage、sessionStorage、cookies
storage: window.sessionStorage,
// 存储的 key 的key值(如果不写默认是vuex)
key: "store",
paths: ['fanSystem', ] //要存的数据模块,如果不配置,默认所有模块的数据都保存
})
]
});
export default store;
分模块之后我们调用mutations、actions里面的方法不变
this.$store.commit[方法名] // mutations
this.$store.dispath[方法名] // actions
去取state里面的数据时,要分模块去取
this.$store.state[模块名][数据名]
这样我们就配置好了,不用自己手写存储的方法了