dictionary.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { type Dictionaries, type DictionaryKeys } from '@/request/api/dictionary.api';
  2. import { tryOnBeforeUnmount } from '@vueuse/core';
  3. import type { ComputedRef, MaybeRefOrGetter } from 'vue';
  4. export function dictionary(
  5. dictionaries: MaybeRefOrGetter<Dictionaries> | ComputedRef<Dictionaries>,
  6. key: DictionaryKeys,
  7. value?: string,
  8. filter?: (value: string) => boolean,
  9. ) {
  10. const options = unref(toRef(dictionaries))?.[ key ] ?? [];
  11. value ??= '';
  12. const _filter = (item?: string) => !!item && (
  13. filter?.(item) ?? true
  14. );
  15. return value
  16. .toString()
  17. .split(',')
  18. .map(value => value.trim().split(':'))
  19. .map(([ key, label ]) => label ?? options.find(item => item.value === key.trim())?.label)
  20. .filter(_filter);
  21. }
  22. export function useDictionary(
  23. dictionaries: MaybeRefOrGetter<Dictionaries> | ComputedRef<Dictionaries>,
  24. key: DictionaryKeys,
  25. value?: MaybeRefOrGetter<any> | ComputedRef<any>,
  26. filter?: (value: string) => boolean,
  27. ) {
  28. const values = shallowRef<string[]>([]);
  29. const stop = watchEffect(() => {
  30. values.value = dictionary(dictionaries, key, value.value, filter ?? (
  31. (v: string) => v !== '无'
  32. ));
  33. });
  34. tryOnBeforeUnmount(() => stop());
  35. return values;
  36. }