index.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * @Author: 廖明明
  3. * @Date: 2022-03-31 16:36:19
  4. * @LastEditors: 廖明明
  5. * @LastEditTime: 2022-04-22 10:16:40
  6. * @Description:vuex入口文件
  7. */
  8. import Vue from "vue";
  9. import Vuex from "vuex";
  10. import other from "./modules/other";
  11. import login from "./modules/login";
  12. import dictionary from "./modules/dictionary";
  13. import system from "./modules/system";
  14. Vue.use(Vuex);
  15. const myPlugin = (store) => {
  16. // 所有的模块配置(新增模块需要手动添加进去)
  17. const customModules = [{
  18. name: 'other',
  19. aliasName: 'Other',
  20. isLocalstorage: true
  21. },
  22. {
  23. name: 'login',
  24. aliasName: 'Login',
  25. isLocalstorage: true
  26. },
  27. {
  28. name: 'dictionary',
  29. aliasName: 'Dictionary',
  30. isLocalstorage: false
  31. },
  32. {
  33. name: 'system',
  34. aliasName: 'System',
  35. isLocalstorage: false
  36. },
  37. ];
  38. // 需要缓存的模块
  39. const localstorageModules = customModules.filter(v => v.isLocalstorage);
  40. // 当 store 初始化后调用
  41. let vuexStorage = uni.getStorageSync("vuexStorage");
  42. if (vuexStorage) {
  43. customModules.forEach(v => {
  44. if (v.isLocalstorage) {
  45. store.commit(`${v.name}/resetVx${v.aliasName}`, vuexStorage[v.name]);
  46. } else {
  47. store.commit(`${v.name}/resetVx${v.aliasName}`);
  48. }
  49. })
  50. }
  51. store.subscribe((mutation, state) => {
  52. const isLocalstorageFlag = localstorageModules.some(v => mutation.type.startsWith(`${v.name}/`));
  53. if (isLocalstorageFlag) {
  54. const obj = {};
  55. localstorageModules.forEach(v => {
  56. obj[v.name] = state[v.name];
  57. })
  58. uni.setStorageSync("vuexStorage", obj);
  59. }
  60. });
  61. };
  62. export default new Vuex.Store({
  63. modules: {
  64. login,
  65. dictionary,
  66. system,
  67. other,
  68. },
  69. plugins: [myPlugin],
  70. });