dict.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { reactive } from 'vue';
  2. import { getDicts } from '@/api/system/dict/data';
  3. import { useDictStore } from '@/store/modules/dict';
  4. /**
  5. * 获取字典数据
  6. */
  7. export const useDict = (...args: string[]) => {
  8. const res = reactive<{ [key: string]: DictDataOption[] }>({});
  9. // 初始化所有字典类型为空数组
  10. args.forEach((dictType) => {
  11. res[dictType] = [];
  12. });
  13. // 使用Promise.all确保所有字典数据都能正确加载
  14. const loadDict = async () => {
  15. try {
  16. const promises = args.map(async (dictType) => {
  17. const dicts = useDictStore().getDict(dictType);
  18. if (dicts && dicts.length > 0) {
  19. res[dictType] = dicts;
  20. return;
  21. }
  22. try {
  23. console.log(`开始加载字典类型: ${dictType}`);
  24. const resp = await getDicts(dictType);
  25. console.log(`字典 ${dictType} API响应:`, resp);
  26. if (resp && resp.data && Array.isArray(resp.data) && resp.data.length > 0) {
  27. // 保留原始数据用于排序
  28. const dictDataRaw = resp.data;
  29. // 按dictSort升序,dictSort相同再按dictValue排序
  30. const sortedDictDataRaw = dictDataRaw.sort((a, b) => {
  31. if (a.dictSort !== b.dictSort) {
  32. return a.dictSort - b.dictSort;
  33. }
  34. // dictSort相同,按dictValue数值排序
  35. const valueA = Number(a.dictValue);
  36. const valueB = Number(b.dictValue);
  37. if (!isNaN(valueA) && !isNaN(valueB)) {
  38. return valueA - valueB;
  39. }
  40. return String(a.dictValue).localeCompare(String(b.dictValue));
  41. });
  42. // 转换为DictDataOption
  43. const dictData = sortedDictDataRaw.map(
  44. (p): DictDataOption => ({
  45. label: p.dictLabel,
  46. value: p.dictValue,
  47. elTagType: p.listClass,
  48. elTagClass: p.cssClass
  49. })
  50. );
  51. res[dictType] = dictData;
  52. useDictStore().setDict(dictType, dictData);
  53. console.log(`字典 ${dictType} 加载成功并按dictSort排序,数据:`, dictData);
  54. } else {
  55. console.warn(`字典类型 ${dictType} 没有返回有效数据,响应:`, resp);
  56. res[dictType] = [];
  57. }
  58. } catch (error) {
  59. console.error(`获取字典类型 ${dictType} 失败:`, error);
  60. res[dictType] = [];
  61. }
  62. });
  63. await Promise.all(promises);
  64. } catch (error) {
  65. console.error('字典数据批量加载失败:', error);
  66. }
  67. };
  68. // 立即执行异步加载
  69. loadDict();
  70. return res;
  71. };