123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- import { saveData, getData, openDB } from "@/utils/indexedDb";
- const vuexIndexedDBPlugin = (store) => {
- const dbName = "vuexDB";
- const keyName = "vuexState";
- // 过滤 Vuex 状态,去掉不可序列化的部分
- const filterState = (state) => {
- const clonedState = JSON.parse(
- JSON.stringify(state, (key, value) => {
- // 如果是函数或无法克隆的对象,返回 undefined
- if (typeof value === "function") return undefined;
- return value;
- })
- );
- return clonedState;
- };
- // 初始化 IndexedDB 并加载状态
- openDB(dbName, 1).then(() => {
- getData(dbName, keyName).then((savedState) => {
- if (savedState) {
- store.replaceState({
- ...store.state,
- ...savedState,
- });
- console.log("Vuex state loaded from IndexedDB");
- }
- });
- });
- // 订阅 Vuex mutations,每次状态变更时保存到 IndexedDB
- store.subscribe((mutation, state) => {
- const serializableState = filterState(state);
- saveData(dbName, keyName, serializableState)
- .then(() => {
- console.log(`Mutation "${mutation.type}" saved state to IndexedDB`);
- })
- .catch((error) => {
- console.error("Failed to save state to IndexedDB:", error);
- });
- });
- };
- export default vuexIndexedDBPlugin;
|