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