vben
2020-12-25 4ff1c408dc1acfc49e0adc61dc2e539c0c198158
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import type { UnwrapRef } from 'vue';
import { reactive, readonly, computed, getCurrentInstance } from 'vue';
 
import { isEqual } from 'lodash-es';
 
export function useRuleFormItem<T extends Indexable>(
  props: T,
  key: keyof T = 'value',
  changeEvent = 'change'
) {
  const instance = getCurrentInstance();
  const emit = instance?.emit;
 
  const innerState = reactive({
    value: props[key],
  });
 
  const defaultState = readonly(innerState);
 
  const setState = (val: UnwrapRef<T[keyof T]>) => {
    innerState.value = val as T[keyof T];
  };
  const state = computed({
    get() {
      return innerState.value;
    },
    set(value) {
      if (isEqual(value, defaultState.value)) return;
      innerState.value = value as T[keyof T];
      emit?.(changeEvent, value);
    },
  });
 
  return [state, setState, defaultState];
}