背景
在我们日常的vue开发中,常常会用到vuex,且愈发广泛。在vue大火之前我们做客户端浏览器的缓存时往往借助于window、Application等浏览器自带的数据共享/存储方案,作为强迫症的我。。。在vue项目中我们更推荐使用vuex,但vuex作为我们项目中一个对象树的存在常常有一些场景受到牵制,比如每次刷新页面的时候vuex对象状态树会自动初始化,如我们需要缓存的token等重要信息需要一定时间一直保存的时候 问题来了 怎么办呢?继续往下看
方案
利用vuex的一款成熟的持久化插件vuex-persistedstate; 借助于原生的浏览器缓存来实现vuex的持久化缓存方案,便捷好用。
安装
第一步先安装
// 终端执行
pnpm install vuex-persistedstate;
使用
- 在store/index.js中 导入包
// store/index.js
import { createStore } from "vuex";
import createPersistedstate from "vuex-persistedstate";
- 在store/index.js中 实例化store的时候初始化插件
plugins: [
createPersistedstate({}),
],
-
增加插件配置 参数说明 配置持久化存储:
存储方式:localStorage、sessionStorage、cookies
storage: window.sessionStorage,
存储的 key 的key值
key: "storeState",
paths: [user_name: state.Login.user_name],
render(state) { 、全部持久化 // 要存储的数据:本项目采用es6扩展运算符的方式存储了state中所有的数据 return { ...state }; },
reducer(state) { return { // 只储存modules中的部分数据 Login: state.Login, aaa: state.aaa }; },
下面直接上代码
import { createStore } from "vuex";
import createPersistedstate from "vuex-persistedstate";
// import Modules from "./modules";
import Login from "./modules/Login";
...
// import getters from "./getters";
// 以下是vux模块
const store = createStore({
state: {
aaa: "",
...
},
mutations: {
...
},
// actions: {},
modules: {
Login,
...
}, // 各位小伙伴使用请注意⚠️: 除自动动态按需注入模块外,还可以在此静态注入模块,注意:动态注入的模块可动态卸载,在此处静态注入的模块不可卸载,会全局注入
// getters,
plugins: [
createPersistedstate({
// 配置持久化存储
// 存储方式:localStorage、sessionStorage、cookies
storage: window.sessionStorage,
// 存储的 key 的key值
key: "storeState",
// paths: [user_name: state.Login.user_name],
// render(state) { // 全部持久化
// // 要存储的数据:本项目采用es6扩展运算符的方式存储了state中所有的数据
// return { ...state };
// },
reducer(state) {
return {
// 只储存modules中的部分数据
Login: state.Login,
aaa: state.aaa
};
},
}),
],
});
export default store;
// 重置state数据
export function clearState(state, initData) {
Object.keys(state).forEach((key) => {
if (!initData[key]) {
delete state[key];
}
});
Object.keys(initData).forEach((key) => {
state[key] = initData[key];
});
}
// 清除store
export function clearStore(index) {
if (!store) return;
const modules = [
"Login",
];
if (index) {
store.commit("clear" + modules[index]);
} else {
modules.forEach((item) => {
store.commit("clear" + item);
});
}
}