-
Notifications
You must be signed in to change notification settings - Fork 0
/
useVirtualField.ts
73 lines (65 loc) · 1.66 KB
/
useVirtualField.ts
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { onBeforeUnmount, onMounted, Ref, ref, unref, watch } from 'vue';
import { Form } from '../form';
import { VirtualFieldRule } from './../types';
import { FormType } from '../types';
import { useForm } from './useForm';
export type UseVirtualFieldProps<
T extends FormType = FormType,
VFK extends string = string,
N extends VFK = VFK,
V = any
> = {
form?: Form<T, VFK>;
name: Ref<N> | N;
value: () => V;
rules?: Ref<VirtualFieldRule[]> | VirtualFieldRule[];
debounce?: number;
};
/**
* @category Use
*/
export const useVirtualField = <T extends FormType, N extends string>(
props: UseVirtualFieldProps<T, N>
): {
mounted: Ref<Boolean>;
} => {
const injectForm = useForm() as Form<T> | null;
const { form = injectForm, name } = props;
if (!form) {
throw new Error('No provided form!');
}
const mounted = ref(false);
let { register, field } = form.registerVirtualField(unref(name), {
value: props.value,
rules: unref(props.rules),
immediate: false,
debounce: props.debounce
});
const fieldState = ref(field.state);
const stopWatch = watch(
() => unref(props.name),
(n, ln) => {
form.unregisterVirtualField(ln);
const fs = form.registerVirtualField(unref(name), {
value: props.value,
rules: unref(props.rules),
immediate: mounted.value,
debounce: props.debounce
});
register = fs.register;
field = fs.field;
fieldState.value = fs.field.state;
}
);
onMounted(() => {
register();
mounted.value = true;
});
onBeforeUnmount(() => {
form.unregisterVirtualField(unref(name));
stopWatch();
});
return {
mounted
};
};