zhangwencui
7 天以前 7619c19a67c2ac824f803090bab753fc5ea14408
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
import { computed, inject } from 'vue';
 
import { FieldContextKey } from 'vee-validate';
 
import { FORM_ITEM_INJECTION_KEY } from './injectionKeys';
 
export function useFormField() {
  const fieldContext = inject(FieldContextKey);
  const fieldItemContext = inject(FORM_ITEM_INJECTION_KEY);
 
  if (!fieldContext)
    throw new Error('useFormField should be used within <FormField>');
 
  const { name, errorMessage: error, meta } = fieldContext;
  const id = fieldItemContext;
 
  const fieldState = {
    valid: computed(() => meta.valid),
    isDirty: computed(() => meta.dirty),
    isTouched: computed(() => meta.touched),
    error,
  };
 
  return {
    id,
    name,
    formItemId: `${id}-form-item`,
    formDescriptionId: `${id}-form-item-description`,
    formMessageId: `${id}-form-item-message`,
    ...fieldState,
  };
}