| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- import { reactive } from 'vue';
- import { getDicts } from '@/api/system/dict/data';
- import { useDictStore } from '@/store/modules/dict';
- /**
- * 获取字典数据
- */
- export const useDict = (...args: string[]) => {
- const res = reactive<{ [key: string]: DictDataOption[] }>({});
- // 初始化所有字典类型为空数组
- args.forEach((dictType) => {
- res[dictType] = [];
- });
- // 使用Promise.all确保所有字典数据都能正确加载
- const loadDict = async () => {
- try {
- const promises = args.map(async (dictType) => {
- const dicts = useDictStore().getDict(dictType);
- if (dicts && dicts.length > 0) {
- res[dictType] = dicts;
- return;
- }
- try {
- console.log(`开始加载字典类型: ${dictType}`);
- const resp = await getDicts(dictType);
- console.log(`字典 ${dictType} API响应:`, resp);
- if (resp && resp.data && Array.isArray(resp.data) && resp.data.length > 0) {
- // 保留原始数据用于排序
- const dictDataRaw = resp.data;
- // 按dictSort升序,dictSort相同再按dictValue排序
- const sortedDictDataRaw = dictDataRaw.sort((a, b) => {
- if (a.dictSort !== b.dictSort) {
- return a.dictSort - b.dictSort;
- }
- // dictSort相同,按dictValue数值排序
- const valueA = Number(a.dictValue);
- const valueB = Number(b.dictValue);
- if (!isNaN(valueA) && !isNaN(valueB)) {
- return valueA - valueB;
- }
- return String(a.dictValue).localeCompare(String(b.dictValue));
- });
- // 转换为DictDataOption
- const dictData = sortedDictDataRaw.map(
- (p): DictDataOption => ({
- label: p.dictLabel,
- value: p.dictValue,
- elTagType: p.listClass,
- elTagClass: p.cssClass
- })
- );
- res[dictType] = dictData;
- useDictStore().setDict(dictType, dictData);
- console.log(`字典 ${dictType} 加载成功并按dictSort排序,数据:`, dictData);
- } else {
- console.warn(`字典类型 ${dictType} 没有返回有效数据,响应:`, resp);
- res[dictType] = [];
- }
- } catch (error) {
- console.error(`获取字典类型 ${dictType} 失败:`, error);
- res[dictType] = [];
- }
- });
- await Promise.all(promises);
- } catch (error) {
- console.error('字典数据批量加载失败:', error);
- }
- };
- // 立即执行异步加载
- loadDict();
- return res;
- };
|