// composables/useDictMapper.js
|
import { ref, toRaw } from 'vue'
|
import { useDict } from '@/utils/dict'
|
|
// 字典数据缓存(单例)
|
const dictCache = new Map()
|
const loadingPromises = new Map() // 避免重复请求
|
|
/**
|
* 加载指定字典类型,带缓存和并发控制
|
* @param {Array<string>} dictTypes 字典类型数组,如 ['sys_user_sex', 'sys_BloodType']
|
* @returns {Promise<Object>} 字典对象 { sys_user_sex: [...], ... }
|
*/
|
async function loadDicts(dictTypes) {
|
const key = dictTypes.sort().join(',')
|
if (dictCache.has(key)) {
|
return dictCache.get(key)
|
}
|
if (loadingPromises.has(key)) {
|
return loadingPromises.get(key)
|
}
|
const promise = (async () => {
|
try {
|
const result = await useDict(...dictTypes)
|
dictCache.set(key, result)
|
return result
|
} finally {
|
loadingPromises.delete(key)
|
}
|
})()
|
loadingPromises.set(key, promise)
|
return promise
|
}
|
|
/**
|
* 字典映射器组合函数
|
* @param {Array<string>} dictTypes 需要的字典类型列表
|
* @returns {Object} { loading, getDictLabel, getGenderText, getBloodTypeText, getAgeUnitText, ... }
|
*/
|
export function useDictMapper(dictTypes = []) {
|
const loading = ref(false)
|
const dictData = ref({})
|
|
const init = async () => {
|
if (dictTypes.length === 0) return
|
loading.value = true
|
try {
|
dictData.value = await loadDicts(dictTypes)
|
} finally {
|
loading.value = false
|
}
|
}
|
|
// 通用字典标签获取
|
const getDictLabel = (dictType, value) => {
|
const list = dictData.value[dictType]
|
if (!list || !Array.isArray(list)) return value
|
const item = list.find(item => item.value == value)
|
return item ? item.label : value
|
}
|
|
// 性别文本
|
const getGenderText = (gender) => {
|
return getDictLabel('sys_user_sex', gender)
|
}
|
|
// 血型文本
|
const getBloodTypeText = (bloodType) => {
|
return getDictLabel('sys_BloodType', bloodType)
|
}
|
|
// 年龄单位文本
|
const getAgeUnitText = (ageunit) => {
|
const unitMap = {
|
year: '岁',
|
month: '个月',
|
day: '天'
|
}
|
return unitMap[ageunit] || ageunit || ''
|
}
|
|
// 如果还有其它字典类型需要映射,可以继续添加方法
|
// 例如证件类型、民族等
|
|
// 立即初始化(不阻塞,但调用方可以 await init() 确保字典已加载)
|
init()
|
|
return {
|
loading,
|
dictData, // 原始字典数据(只读)
|
getDictLabel, // 通用方法
|
getGenderText,
|
getBloodTypeText,
|
getAgeUnitText,
|
// 可扩展其他映射
|
}
|
}
|