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
|
}
|