appStore.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import { defineStore } from 'pinia';
  2. import { AppStoreState, ConfigItem, DictItem, PickerItem } from '@/types';
  3. import { getConfig, getProvinces } from '@/api/modules/system';
  4. import { useDictStore } from '@/store/dictStore';
  5. import { EnumDictName } from '@/common/enum';
  6. import { useUserStore } from '@/store/userStore';
  7. const preloadDicts: string[] = [
  8. EnumDictName.EXAM_TYPE
  9. ];
  10. export const useAppStore = defineStore('ie-app', {
  11. state: (): AppStoreState => {
  12. return {
  13. isInitialized: false,
  14. activeTabbar: 0,
  15. statusBarHeight: 0,
  16. sysInfo: null as UniApp.GetSystemInfoResult | null,
  17. appConfig: [] as ConfigItem[],
  18. }
  19. },
  20. getters: {
  21. systemInfo(): UniApp.GetSystemInfoResult {
  22. if (!this.sysInfo) {
  23. return uni.getSystemInfoSync();
  24. }
  25. return this.sysInfo;
  26. }
  27. },
  28. actions: {
  29. async init() {
  30. this.clear();
  31. try {
  32. const dictStore = useDictStore();
  33. // 预加载字典数据
  34. dictStore.loadDicts(preloadDicts).then(finish => { });
  35. const userStore = useUserStore();
  36. if (userStore.isLogin) {
  37. await userStore.getUserInfo();
  38. }
  39. this.isInitialized = true;
  40. this.sysInfo = uni.getSystemInfoSync();
  41. await this.loadPreloadData();
  42. return Promise.resolve(true);
  43. } catch (error) {
  44. console.error('初始化数据失败:', error);
  45. return Promise.resolve(false);
  46. }
  47. },
  48. /**
  49. * 加载前置必要数据
  50. */
  51. async loadPreloadData() {
  52. await this.loadConfig();
  53. },
  54. /**
  55. * 加载参数配置
  56. */
  57. async loadConfig() {
  58. const { data } = await getConfig();
  59. const list: ConfigItem[] = [];
  60. data.forEach(item => {
  61. // 只保留需要的字段
  62. list.push({
  63. configKey: item.configKey,
  64. configValue: item.configValue,
  65. configType: item.configType,
  66. configName: item.configName,
  67. configId: item.configId,
  68. } as ConfigItem);
  69. });
  70. this.appConfig = list;
  71. },
  72. /**
  73. * 获取应用配置项的值
  74. * @param key 配置项的 key
  75. * @returns 配置项的 value,如果不存在则返回 undefined
  76. */
  77. getAppConfig(key: string): string | undefined {
  78. return this.appConfig.find(item => item.configKey === key)?.configValue;
  79. },
  80. setActiveTabbar(index: number) {
  81. this.activeTabbar = index;
  82. },
  83. clear() {
  84. this.isInitialized = false;
  85. }
  86. },
  87. persist: {
  88. storage: {
  89. getItem: uni.getStorageSync,
  90. setItem: uni.setStorageSync,
  91. },
  92. // 不需要持久化的
  93. // 'appConfig'
  94. omit: [],
  95. }
  96. });