WXL
昨天 c80bc467a41daa6cbae4e5515a300a8ca98cfeaa
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// 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,
    // 可扩展其他映射
  }
}