dict.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import dictEnum, { numberList } from '@/enum/dict';
  2. import Vue from 'vue';
  3. import { getByCode } from '@/api/system/dictionary-data';
  4. //非枚举定义
  5. // const otherDictConfig = {
  6. // // [dictEnum.物品类型]: {
  7. // // request: getSubListByParentId,
  8. // // dictCode: 'type',
  9. // // dictValue: 'name',
  10. // // resKey: '' //为空选 data
  11. // // }
  12. // };
  13. const state = {
  14. // 加载中的字典项
  15. dictLoading: []
  16. };
  17. const mutations = {
  18. //根据字典code 添加字典
  19. ADD_DICT: (state, { code, dict }) => {
  20. Vue.set(state, code, dict);
  21. },
  22. dictLoadingAdd: (state, code) => {
  23. state.dictLoading.push(code);
  24. },
  25. dictLoadingRemove: (state, code) => {
  26. state.dictLoading = state.dictLoading.filter((item) => item !== code);
  27. }
  28. };
  29. const actions = {
  30. // 根据字典enumName请求字典 已获取的不做重复请求
  31. async requestDict({ commit, state }, enumName) {
  32. const code = dictEnum[enumName];
  33. // 如果字典正在加载中,则不重复请求
  34. if (state.dictLoading.includes(code)) return;
  35. commit('dictLoadingAdd', code);
  36. if (state[code]?.length) return state[code];
  37. try {
  38. let res = await getByCode(code);
  39. if (res?.code == 0) {
  40. const isNumber = numberList.includes(code);
  41. commit('ADD_DICT', {
  42. code,
  43. dict: res.data.map((item) => {
  44. const arr = Object.entries(item)[0] || [];
  45. return {
  46. dictCode: isNumber ? Number(arr[0]) : arr[0],
  47. dictValue: arr[1]
  48. };
  49. })
  50. });
  51. commit('dictLoadingRemove', code);
  52. return res.data;
  53. }
  54. commit('dictLoadingRemove', code);
  55. return [];
  56. } catch (error) {
  57. commit('dictLoadingRemove', code);
  58. return [];
  59. }
  60. },
  61. // 更新字典
  62. async reloadRequestDict({ commit }, enumName) {
  63. const code = dictEnum[enumName];
  64. const res = await getByCode(code);
  65. const isNumber = numberList.includes(code);
  66. if (res?.code == 0) {
  67. commit('ADD_DICT', {
  68. code,
  69. dict: res.data.map((item) => {
  70. const arr = Object.entries(item);
  71. return {
  72. dictCode: isNumber ? Number(arr[0]) : arr[0],
  73. dictValue: arr[1]
  74. };
  75. })
  76. });
  77. return res.data;
  78. }
  79. return [];
  80. }
  81. };
  82. export default {
  83. namespaced: true,
  84. state,
  85. mutations,
  86. actions
  87. };