cascader.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { Ref, computed } from "vue";
  2. export type CascaderOptions = {
  3. label: string;
  4. value: string;
  5. children?: CascaderOptions;
  6. }[];
  7. export const splitChar = ">";
  8. export const getValue = (val: string) => val.split(splitChar);
  9. export const getRaw = (val: string[]) => val.join(splitChar);
  10. export const genCascaderValue = <
  11. K extends string,
  12. T extends Ref<{ [key in K]: string }>
  13. >(
  14. target: T,
  15. key: K,
  16. def?: string
  17. ) =>
  18. computed({
  19. get: () =>
  20. target.value[key]
  21. ? target.value[key].split(">")
  22. : def
  23. ? [def]
  24. : undefined,
  25. set: (val) => (target.value[key] = val!.join(">")),
  26. });
  27. export const getCode = (options: CascaderOptions, raw: string) => {
  28. const paths = getValue(raw);
  29. let current = options;
  30. let rets = "";
  31. for (let val of paths) {
  32. const idx = current.findIndex(({ value }) => value === val);
  33. if (~idx) {
  34. rets += idx + 1;
  35. if (current[idx].children) {
  36. current = current[idx].children!;
  37. } else {
  38. break;
  39. }
  40. } else {
  41. // rets += "0";
  42. break;
  43. }
  44. }
  45. return rets;
  46. };