vuex和数据持久化
前端将所需数据存储在vuex中,但是vuex中数据在刷新后会被清空,
而数据持久化,就是在执行浏览器刷新操作时,将vuex中的数据转存在本地localstorge中,
在刷新时先去local中取,取到之后渲染到页面,
再将数据转存到vuex中,清空localstorge,也就实现了数据的持久化
vuex中
1.store/index.js
import Vue from "vue";
import Vuex from "vuex";
import modules from "./modules";
import getters from "./getters";
import createPersistedState from "vuex-persistedstate";
Vue.use(Vuex);
const createPersisted = createPersistedState({
storage: window.sessionStorage,
key: 'CHEN',
reducer (val) {
return {
// 只储存state中的某些字段 注意:键值对名字要一致
// tagsView: val.tagsView,
// user: val.user
home: val.home
};
}
});
const store = new Vuex.Store({
modules: {...modules},
getters,
strict: process.env.NODE_ENV !== "production",
plugins: [createPersisted]
});
export default store;
2.store/modules/index.js
const files = require.context('.', true, /\.module.js$/);
let modules = {};
files.keys().forEach((key) => {
let temp = modules[key.replace(/(\.\/|\.module.js)/g, '')];
if (!temp) {
temp = {};
}
modules[key.replace(/(\.\/|\.module.js)/g, '')] = Object.assign(
temp,
files(key).default
);
});
console.log(modules,'modules');
export default modules;
3.store/modules/dataCache.modules.js
const dataCache = {
state: {
params: {}
},
mutations: {
SET_CACHE_PARAMS: (state, payload) => {
if (payload.params) {
state.params[payload.moduleName] = payload.params;
} else {
delete state.params[payload.moduleName];
}
}
}
};
export default dataCache;
store/modules/home.modules.js
const home = {
namespaced: true,
state: {
homeFlag: 123
},
mutations: {
aMutations: (state, data) => {
state.homeFlag = 567;
}
},
actions: {
homeActions({ commit }, data) {
commit('aMutations');
}
}
};
export default home;
安装: npm i -S vuex-persistedstate
配置使用:
import createPersistedState from "vuex-persistedstate";
const createPersisted = createPersistedState({
storage: window.sessionStorage,
key: 'CHEN',
reducer (val) {
return {
// 只储存state中的某些字段 注意:键值对名字要一致
// tagsView: val.tagsView,
// user: val.user
home: val.home
};
}
});