_dict.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import apis from "../api"
  2. const DICT_KEY = "DICK_CACHE"
  3. export const useDictStore = defineStore("dict", () => {
  4. const dictArr = ref<any[]>(localCache.getJSON(DICT_KEY) || [])
  5. // 获取字典
  6. function getDict(key: string) {
  7. return new Promise((resolve, reject) => {
  8. if (key == null && key == "") {
  9. reject(new Error("Key 不能为空"))
  10. return
  11. }
  12. let item = dictArr.value?.find((v) => v.key == key)
  13. if (item == null) {
  14. apis.system.dictApi.getDicts(key).then((res: any) => {
  15. if (res.code == 200) {
  16. item = formatterDict(key, res.data)
  17. resolve(item)
  18. } else {
  19. reject(res.message)
  20. }
  21. })
  22. } else {
  23. resolve(item.value)
  24. }
  25. })
  26. }
  27. function setDict(key: string, value: string) {
  28. if (key !== null && key !== "") {
  29. dictArr.value = dictArr.value || []
  30. dictArr.value.push({
  31. key,
  32. value
  33. })
  34. localCache.setJSON(DICT_KEY, dictArr.value)
  35. }
  36. }
  37. function removeDict(key: string) {
  38. const index = dictArr.value.findIndex((v) => {
  39. return v.key == key
  40. })
  41. if (index > 0) {
  42. dictArr.value.splice(index, 1)
  43. }
  44. }
  45. function formatterDict(key: string, data: any, custFormat?: (v: any) => any) {
  46. // console.log("DATA", data)
  47. let dict: any = {}
  48. if (data?.length) {
  49. dict = data.map((p: any) => ({
  50. label: p.dictLabel,
  51. value: p.dictValue,
  52. elTagType: p.listClass,
  53. elTagClass: p.cssClass
  54. }))
  55. setDict(key, dict)
  56. if (custFormat) {
  57. dict = custFormat(data)
  58. }
  59. }
  60. return dict
  61. }
  62. // 清空字典
  63. function cleanDict() {
  64. return new Promise((resolve, reject) => {
  65. apis.system.dictApi
  66. .refreshCache()
  67. .then(() => {
  68. dictArr.value = []
  69. localCache.setJSON(DICT_KEY, [])
  70. resolve("")
  71. })
  72. .catch((e) => {
  73. reject(e)
  74. })
  75. })
  76. }
  77. function initDict() {
  78. dictArr.value = localCache.getJSON(DICT_KEY)
  79. if (dictArr.value && dictArr.value.length > 0) {
  80. return
  81. }
  82. apis.system.dictApi.listAllType().then((res: any) => {
  83. if (res.code == 200) {
  84. res.data.forEach((v: any) => {
  85. getDict(v.dictType)
  86. })
  87. }
  88. })
  89. }
  90. return {
  91. getDict,
  92. setDict,
  93. removeDict,
  94. cleanDict,
  95. formatterDict,
  96. initDict
  97. }
  98. })