| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- import { ref } from 'vue'
- import * as pubApi from '@/api/pub'
- export interface DictItem {
- label: string
- value: ID
- }
- /**
- * 获取指定类型的字典数据,并返回列表和映射表
- *
- * @param dicType 字典类型标识,例如 'institution_type'、'guardianship_type' 等
- * @example 返回值结构:
- * {
- * dictList: Ref<DictItem[]> 字典项列表,包含 label 和 value
- * dictNameMap: Ref<Record<string, string>> 字典项映射表,value → label
- * fetchDict: () => Promise<void> 异步方法,用于拉取字典数据
- * }
- *
- * @example 使用示例:
- * const { dictList, dictNameMap, fetchDict } = useDict('institution_type')
- * await fetchDict()
- * const name = dictNameMap.value['A01'] || '未知'
- *
- * @enum {string}
- * institution_type 机构类型
- * * guardianship_type 监护类型
- * * device_type 设备类型
- * * install_position 安装位置
- */
- export const useDict = (dicType: string) => {
- const dictList = ref<DictItem[]>([])
- const dictNameMap = ref<Record<string, string>>({})
- const fetchDict = async () => {
- console.log('👏👏👏useDict fetchDict', dicType)
- try {
- const res = await pubApi.queryDictList({ dicType })
- const data = res.data || []
- dictList.value = Array.isArray(data)
- ? data.map((item) => ({
- label: item.itemName,
- value: item.itemCode,
- }))
- : []
- // 构建 value → label 映射表
- dictNameMap.value = Object.fromEntries(dictList.value.map((item) => [item.value, item.label]))
- } catch (error) {
- console.error('获取字典数据失败:', error)
- dictList.value = []
- dictNameMap.value = {}
- }
- }
- return {
- dictList,
- dictNameMap,
- fetchDict,
- }
- }
|