dict.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // src/mixins/useDictMixin.js
  2. import { getDicts } from '@/api/system/dict/data';
  3. export default {
  4. methods: {
  5. async useDict(...args) {
  6. const res = {};
  7. for (const dictType of args) {
  8. let dicts = this.getDictFromStore(dictType);
  9. if (!dicts) {
  10. try {
  11. const response = await getDicts(dictType);
  12. dicts = response.data.map(p => ({
  13. label: p.dictLabel,
  14. value: p.dictValue,
  15. elTagType: p.listClass,
  16. elTagClass: p.cssClass
  17. }));
  18. res[dictType] = dicts;
  19. this.setDictToStore(dictType, dicts);
  20. } catch (err) {
  21. console.error(`获取字典 ${dictType} 失败`, err);
  22. res[dictType] = [];
  23. }
  24. } else {
  25. res[dictType] = dicts;
  26. }
  27. }
  28. return res;
  29. },
  30. getDictFromStore(key) {
  31. if (!key) return null;
  32. const item = this.$store.state.dict.dict.find(item => item.key === key);
  33. return item ? item.value : null;
  34. },
  35. setDictToStore(key, value) {
  36. this.$store.dispatch('dict/setDict', { key, value }, { root: true });
  37. }
  38. }
  39. }