vuexIndexedDBPlugin.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { saveData, getData, openDB } from "@/utils/indexedDb";
  2. const vuexIndexedDBPlugin = (store) => {
  3. const dbName = "vuexDB";
  4. const keyName = "vuexState";
  5. // 过滤 Vuex 状态,去掉不可序列化的部分
  6. const filterState = (state) => {
  7. const clonedState = JSON.parse(
  8. JSON.stringify(state, (key, value) => {
  9. // 如果是函数或无法克隆的对象,返回 undefined
  10. if (typeof value === "function") return undefined;
  11. return value;
  12. })
  13. );
  14. return clonedState;
  15. };
  16. // 初始化 IndexedDB 并加载状态
  17. openDB(dbName, 1).then(() => {
  18. getData(dbName, keyName).then((savedState) => {
  19. if (savedState) {
  20. store.replaceState({
  21. ...store.state,
  22. ...savedState,
  23. });
  24. console.log("Vuex state loaded from IndexedDB");
  25. }
  26. });
  27. });
  28. // 订阅 Vuex mutations,每次状态变更时保存到 IndexedDB
  29. store.subscribe((mutation, state) => {
  30. const serializableState = filterState(state);
  31. saveData(dbName, keyName, serializableState)
  32. .then(() => {
  33. console.log(`Mutation "${mutation.type}" saved state to IndexedDB`);
  34. })
  35. .catch((error) => {
  36. console.error("Failed to save state to IndexedDB:", error);
  37. });
  38. });
  39. };
  40. export default vuexIndexedDBPlugin;