yubo
2026-04-06 6448ec15bfe0b65fb822a662105bceddc23b58d8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { getAllDicitemsAll } from '@/api/data'
import db from '@/utils/localstorage'
 
const DICT_STORAGE_KEY = 'ALL_DICT_DATA'
 
// 从 localStorage 恢复字典数据
const restoreDictFromStorage = () => {
  return db.get(DICT_STORAGE_KEY, [])
}
 
const state = {
  allDictData: restoreDictFromStorage(),
  dictLoaded: restoreDictFromStorage().length > 0,
  loading: false // 添加 loading 锁,防止并发请求
}
 
const mutations = {
  SET_ALL_DICT_DATA(state, data) {
    state.allDictData = data
    state.dictLoaded = true
    // 持久化到 localStorage
    db.save(DICT_STORAGE_KEY, data)
  },
  SET_LOADING(state, loading) {
    state.loading = loading
  }
}
 
const actions = {
  // 获取所有字典数据
  async LoadAllDicts({ commit, state }) {
    // 已加载直接返回
    if (state.dictLoaded && state.allDictData.length > 0) {
      return state.allDictData
    }
    // 如果正在加载中,等待加载完成
    if (state.loading) {
      // 轮询等待加载完成
      return new Promise((resolve) => {
        const checkLoaded = setInterval(() => {
          if (!state.loading && state.dictLoaded) {
            clearInterval(checkLoaded)
            resolve(state.allDictData)
          }
        }, 100)
      })
    }
    // 开始加载
    commit('SET_LOADING', true)
    try {
      const response = await getAllDicitemsAll()
      const data = response || []
      commit('SET_ALL_DICT_DATA', data)
      return data
    } catch (error) {
      console.error('加载字典数据失败:', error)
      return []
    } finally {
      commit('SET_LOADING', false)
    }
  }
}
 
const getters = {
  // 根据类型获取字典
  getDictByType: (state) => (dictType) => {
    // console.log('dicType=', dictType)
    //  console.log('data', state.allDictData)
    return state.allDictData.filter(item => item.dicCode === dictType)
  },
  // 获取所有字典数据
  allDictData: state => state.allDictData,
  // 是否已加载
  dictLoaded: state => state.dictLoaded
}
 
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}