| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- import {addUser, editUser} from '@apis';
- import {usePutData} from '@hooks';
- import {AddUserParams} from '@models';
- import {formatValidateError} from '@utils';
- import {toTypedSchema} from '@vee-validate/zod';
- import {useForm} from 'vee-validate';
- import {Ref, watchEffect} from 'vue';
- import {object, string} from 'zod';
- export function useFormState(
- id: Ref<string>,
- visible: Ref<boolean>,
- options: {onFetch: () => void, onClose: () => void},
- ) {
- const {handleSubmit, setErrors, setValues} = useForm<AddUserParams>({
- initialValues: {
- userName: '',
- realName: '',
- email: '',
- phone: '',
- role: '',
- },
- validationSchema: toTypedSchema(object({
- userName: string(formatValidateError('user.modal.errors[0]'))
- .min(1, 'user.modal.errors[0]'),
- realName: string(formatValidateError('user.modal.errors[1]'))
- .min(1, 'user.modal.errors[1]'),
- email: string(formatValidateError('user.modal.errors[2]'))
- .email('user.modal.errors[3]'),
- phone: string(formatValidateError('user.modal.errors[4]'))
- .min(1, 'user.modal.errors[4]'),
- role: string(formatValidateError('user.modal.errors[5]'))
- .min(1, 'user.modal.errors[5]'),
- })),
- });
- watchEffect(function() {
- if (visible.value) {
- setErrors({
- userName: void 0,
- realName: void 0,
- email: void 0,
- phone: void 0,
- role: void 0,
- });
- }
- });
- const {onFetch, onClose} = options;
- const [isLoading, {addMutate, editMutate}] = usePutData({
- addFn: addUser,
- editFn: editUser,
- onFetch,
- onClose,
- });
- const onSubmit = handleSubmit(function(val) {
- id.value.length > 0
- ? editMutate({id: id.value, ...val})
- : addMutate(val);
- });
- return [isLoading, {setValues, onSubmit}] as const;
- }
|