dictStore.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { defineStore } from 'pinia';
  2. import { getDictData } from '@/api/modules/system';
  3. import { DictItem, DictStoreState } from '@/types';
  4. export const useDictStore = defineStore('ie-dict', {
  5. state: (): DictStoreState => {
  6. return {
  7. dicts: {}
  8. }
  9. },
  10. getters: {
  11. },
  12. actions: {
  13. async loadDicts(dictNames: string[]) {
  14. if (!dictNames.length) {
  15. return Promise.resolve(true);
  16. }
  17. for (const dictName of dictNames) {
  18. if (this.dicts[dictName]) {
  19. continue;
  20. }
  21. this.dicts[dictName] = [];
  22. }
  23. const name = dictNames.join(',');
  24. const { data } = await getDictData(name);
  25. for (const dictName in data) {
  26. this.dicts[dictName].push(...data[dictName]);
  27. }
  28. return await Promise.resolve(true);
  29. },
  30. async loadDict(dictName: string) {
  31. if (this.dicts[dictName]) {
  32. return Promise.resolve(true);
  33. }
  34. return await this.loadDicts([dictName]);
  35. },
  36. getDictLabel(dictName: string, value: string | number) {
  37. if (!value) {
  38. return value;
  39. }
  40. const dict = this.dicts[dictName];
  41. if (!dict) {
  42. this.loadDicts([dictName]);
  43. return value;
  44. }
  45. return dict.find((item) => item.dictValue === value)?.dictLabel || value;
  46. },
  47. getDictValue(dictName: string, value: string | number) {
  48. if (!value) {
  49. return value;
  50. }
  51. const dict = this.dicts[dictName];
  52. return dict.find((item) => item.dictValue === value)?.dictValue || value;
  53. },
  54. getDictValues(dictName: string) {
  55. if (!this.dicts[dictName]) {
  56. this.loadDicts([dictName]);
  57. }
  58. return this.dicts[dictName] || [];
  59. },
  60. clear() {
  61. this.dicts = {};
  62. }
  63. }
  64. });