index.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { reactive, toRefs, onUnmounted } from 'vue'
  2. import { enumType } from '@/services/api/common'
  3. export function useEnum(code: string) {
  4. const state = reactive({
  5. loading: true,
  6. enums: <Model.EnumTypeRsp[]>[]
  7. })
  8. const controller = new AbortController()
  9. const readyCallbackMap = new Map<symbol, () => void>()
  10. // 获取枚举名称
  11. const getEnumTypeName = (value: number) => {
  12. const item = state.enums.find((e) => e.enumitemname === value)
  13. const { enumdicname = value?.toString() } = item ?? {}
  14. return enumdicname
  15. }
  16. // 获取枚举列表
  17. const getEnumOptions = (filtered: number | number[] = [], reverse = false) => {
  18. const valuesSet = new Set(Array.isArray(filtered) ? filtered : [filtered])
  19. const result = state.enums.map((e) => ({
  20. label: e.enumdicname,
  21. value: e.enumitemname
  22. }))
  23. if (valuesSet.size > 0) {
  24. if (reverse) {
  25. // 排除枚举
  26. return result.filter((e) => !valuesSet.has(e.value))
  27. } else {
  28. // 匹配枚举
  29. return result.filter((e) => valuesSet.has(e.value))
  30. }
  31. }
  32. return result
  33. }
  34. // 注册成功回调
  35. const registerEnumReadyCallback = (callback: () => void) => {
  36. if (state.loading) {
  37. const key = Symbol()
  38. readyCallbackMap.set(key, callback)
  39. } else {
  40. callback()
  41. }
  42. }
  43. // 获取枚举列表
  44. enumType({
  45. controller,
  46. data: {
  47. typeCode: code
  48. }
  49. }).then((res) => {
  50. state.enums = res.data
  51. readyCallbackMap.forEach((callback) => callback())
  52. readyCallbackMap.clear()
  53. })
  54. onUnmounted(() => {
  55. controller.abort()
  56. readyCallbackMap.clear()
  57. })
  58. return {
  59. ...toRefs(state),
  60. getEnumOptions,
  61. getEnumTypeName,
  62. registerEnumReadyCallback
  63. }
  64. }