useFormItem.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import type { UnwrapRef, Ref, WritableComputedRef, DeepReadonly } from 'vue';
  2. import { reactive, readonly, computed, getCurrentInstance, watchEffect, unref, toRaw } from 'vue';
  3. import { isEqual } from 'lodash-es';
  4. export function useRuleFormItem<T extends Recordable, K extends keyof T, V = UnwrapRef<T[K]>>(
  5. props: T,
  6. key?: K,
  7. changeEvent?,
  8. emitData?: Ref<any[]>,
  9. ): [WritableComputedRef<V>, (val: V) => void, DeepReadonly<V>];
  10. export function useRuleFormItem<T extends Recordable>(
  11. props: T,
  12. key: keyof T = 'value',
  13. changeEvent = 'change',
  14. emitData?: Ref<any[]>,
  15. ) {
  16. const instance = getCurrentInstance();
  17. const emit = instance?.emit;
  18. const innerState = reactive({
  19. value: props[key],
  20. });
  21. const defaultState = readonly(innerState);
  22. const setState = (val: UnwrapRef<T[keyof T]>): void => {
  23. innerState.value = val as T[keyof T];
  24. };
  25. watchEffect(() => {
  26. innerState.value = props[key];
  27. });
  28. const state: any = computed({
  29. get() {
  30. return innerState.value;
  31. },
  32. set(value) {
  33. if (isEqual(value, defaultState.value)) return;
  34. innerState.value = value as T[keyof T];
  35. setTimeout(() => {
  36. emit?.(changeEvent, value, ...(toRaw(unref(emitData)) || []));
  37. });
  38. },
  39. });
  40. return [state, setState, defaultState];
  41. }