hooks.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import {addUser, editUser} from '@apis';
  2. import {usePutData} from '@hooks';
  3. import {AddUserParams} from '@models';
  4. import {formatValidateError} from '@utils';
  5. import {toTypedSchema} from '@vee-validate/zod';
  6. import {useForm} from 'vee-validate';
  7. import {Ref, watchEffect} from 'vue';
  8. import {object, string} from 'zod';
  9. export function useFormState(
  10. id: Ref<string>,
  11. visible: Ref<boolean>,
  12. options: {onFetch: () => void, onClose: () => void},
  13. ) {
  14. const {handleSubmit, setErrors, setValues} = useForm<AddUserParams>({
  15. initialValues: {
  16. userName: '',
  17. realName: '',
  18. email: '',
  19. phone: '',
  20. role: '',
  21. },
  22. validationSchema: toTypedSchema(object({
  23. userName: string(formatValidateError('user.modal.errors[0]'))
  24. .min(1, 'user.modal.errors[0]'),
  25. realName: string(formatValidateError('user.modal.errors[1]'))
  26. .min(1, 'user.modal.errors[1]'),
  27. email: string(formatValidateError('user.modal.errors[2]'))
  28. .email('user.modal.errors[3]'),
  29. phone: string(formatValidateError('user.modal.errors[4]'))
  30. .min(1, 'user.modal.errors[4]'),
  31. role: string(formatValidateError('user.modal.errors[5]'))
  32. .min(1, 'user.modal.errors[5]'),
  33. })),
  34. });
  35. watchEffect(function() {
  36. if (visible.value) {
  37. setErrors({
  38. userName: void 0,
  39. realName: void 0,
  40. email: void 0,
  41. phone: void 0,
  42. role: void 0,
  43. });
  44. }
  45. });
  46. const {onFetch, onClose} = options;
  47. const [isLoading, {addMutate, editMutate}] = usePutData({
  48. addFn: addUser,
  49. editFn: editUser,
  50. onFetch,
  51. onClose,
  52. });
  53. const onSubmit = handleSubmit(function(val) {
  54. id.value.length > 0
  55. ? editMutate({id: id.value, ...val})
  56. : addMutate(val);
  57. });
  58. return [isLoading, {setValues, onSubmit}] as const;
  59. }