介绍
Vuex、Pinia 状态仓库持久化
# 🎏 Vuex 持久化
vuex中引用自定义persistPlugin 插件,
import { createStore } from 'vuex';
import persistPlugin from '/persistPlugin'; // 引入自定义的插件
const store = createStore({
state: {
count: 0
},
modules:{
count: 1
},
persistPlugin:[persistPlugin], //自己调用立即执行
});
export default store;
# persistPlugin.js 插件代码
// persistPlugin.js
export default function persistPlugin(store) { // 调用时会传入store 整个仓库对象
// 存
// store.subscribe((mutation, state) => { // 监听器, 数据发生变化就开始存
// // 每次mutation后调用
// console.log(mutation, state);
// localStorage.setItem('store', JSON.stringify(state));
// });
// 监听浏览器关闭页面或者刷新页面
window.addEventListener('beforeunload', () => {
localStorage.setItem('store', JSON.stringify(store.state));
}
// 一开始就直接读取
// 取
const store = localStorage.getItem('store');
if (store) { // 如果有就替换
store.replaceState(JSON.parse(store));
}
}
# 🎏 Pinia 持久化
pinia的仓库与vuex 有点差异, 它可以有多仓库是比较分散的但逻辑都是差不多的
main中
import { createPinia } from 'pinia';
import persistPlugin from './persistPlugin';
const pinia = createPinia();
app.use(pinia);
pinia.use(persistPlugin); // 导入persistPlugin 插件
persistPlugin.js 插件
// persistPlugin.js
export default function persistPlugin(context) { // pinia 传入的不是整个对象,而是一个上下文, 将每个仓库都传过来
// 存
const key = context.store.$id;
window.addEventListener('beforeunload', () => {
localStorage.setItem(key, JSON.stringify(context.store.$state));
});
// context.$subscribe((store) => {
// localStorage.setItem (key, JSON.stringify(context.store.$state));
// });
// 取
const state = localStorage.getItem(key);
if (state) {
context.store.$patch(JSON.parse(state)); // 替换
}
}
