useDict.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { ref } from 'vue'
  2. import * as pubApi from '@/api/pub'
  3. export interface DictItem {
  4. label: string
  5. value: ID
  6. }
  7. /**
  8. * 获取指定类型的字典数据,并返回列表和映射表
  9. *
  10. * @param dicType 字典类型标识,例如 'institution_type'、'guardianship_type' 等
  11. * @example 返回值结构:
  12. * {
  13. * dictList: Ref<DictItem[]> 字典项列表,包含 label 和 value
  14. * dictNameMap: Ref<Record<string, string>> 字典项映射表,value → label
  15. * fetchDict: () => Promise<void> 异步方法,用于拉取字典数据
  16. * }
  17. *
  18. * @example 使用示例:
  19. * const { dictList, dictNameMap, fetchDict } = useDict('institution_type')
  20. * await fetchDict()
  21. * const name = dictNameMap.value['A01'] || '未知'
  22. *
  23. * @enum {string}
  24. * institution_type 机构类型
  25. * * guardianship_type 监护类型
  26. * * device_type 设备类型
  27. * * install_position 安装位置
  28. */
  29. export const useDict = (dicType: string) => {
  30. const dictList = ref<DictItem[]>([])
  31. const dictNameMap = ref<Record<string, string>>({})
  32. const fetchDict = async () => {
  33. console.log('👏👏👏useDict fetchDict', dicType)
  34. try {
  35. const res = await pubApi.queryDictList({ dicType })
  36. const data = res.data || []
  37. dictList.value = Array.isArray(data)
  38. ? data.map((item) => ({
  39. label: item.itemName,
  40. value: item.itemCode,
  41. }))
  42. : []
  43. // 构建 value → label 映射表
  44. dictNameMap.value = Object.fromEntries(dictList.value.map((item) => [item.value, item.label]))
  45. } catch (error) {
  46. console.error('获取字典数据失败:', error)
  47. dictList.value = []
  48. dictNameMap.value = {}
  49. }
  50. }
  51. return {
  52. dictList,
  53. dictNameMap,
  54. fetchDict,
  55. }
  56. }