luoawai
2023-04-05 6b30c9f7bb97be4ad0af33b99072ec8bef26af90
提交 | 用户 | age
a0165d 1 import type { UnwrapRef, Ref, WritableComputedRef, DeepReadonly } from 'vue';
6b30c9 2 import { reactive, readonly, computed, getCurrentInstance, watchEffect, unref, toRaw, nextTick } from 'vue';
4ff1c4 3
V 4 import { isEqual } from 'lodash-es';
5
a0165d 6 export function useRuleFormItem<T extends Recordable, K extends keyof T, V = UnwrapRef<T[K]>>(
P 7   props: T,
8   key?: K,
9   changeEvent?,
10   emitData?: Ref<any[]>,
11 ): [WritableComputedRef<V>, (val: V) => void, DeepReadonly<V>];
12
a98835 13 export function useRuleFormItem<T extends Recordable>(
4ff1c4 14   props: T,
V 15   key: keyof T = 'value',
fa64fc 16   changeEvent = 'change',
56a966 17   emitData?: Ref<any[]>,
4ff1c4 18 ) {
V 19   const instance = getCurrentInstance();
20   const emit = instance?.emit;
21
22   const innerState = reactive({
23     value: props[key],
24   });
25
26   const defaultState = readonly(innerState);
27
a09a0e 28   const setState = (val: UnwrapRef<T[keyof T]>): void => {
4ff1c4 29     innerState.value = val as T[keyof T];
V 30   };
116a1f 31
V 32   watchEffect(() => {
33     innerState.value = props[key];
34   });
35
4f20d4 36   const state: any = computed({
4ff1c4 37     get() {
V 38       return innerState.value;
39     },
40     set(value) {
41       if (isEqual(value, defaultState.value)) return;
3c4de9 42
4ff1c4 43       innerState.value = value as T[keyof T];
6b30c9 44       nextTick(()=>{
L 45         emit?.(changeEvent, value, ...(toRaw(unref(emitData)) || []));
46       })
4ff1c4 47     },
V 48   });
49
50   return [state, setState, defaultState];
51 }