1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- import { reactive } from 'vue'
- import { object, setLocale, AnySchema, ValidationError } from 'yup'
- import { debounce } from 'lodash-es'
- import Toast from '@/components/toast'
- type FormSchemaShap<T> = {
- [K in keyof T]?: AnySchema
- }
- interface FormOptions<T> {
- initialValues?: Partial<T>
- valuesRef?: T
- schema: FormSchemaShap<T>
- }
- export default function useForm<Shap extends object>(
- options: FormOptions<Shap>
- ) {
- const values: Partial<Shap> =
- options.valuesRef || reactive<Partial<Shap>>(options.initialValues || {})
- const handleSubmit = debounce(
- function (
- onSubmit: (values: Partial<Shap>) => any,
- onInvalidSubmit?: (error: ValidationError) => any
- ) {
- object(options.schema as any)
- .validate(values)
- .then(() => onSubmit(values))
- .catch((err: ValidationError) => {
- Toast(err.message)
- onInvalidSubmit?.(err)
- })
- },
- 500,
- { leading: true, trailing: false }
- )
- const reset = () => {
- Object.keys(values).forEach(key => delete (values as any)[key])
- }
- return { values, handleSubmit, reset }
- }
- setLocale({
- mixed: {
- required: '${path} is required',
- },
- string: {
- email: 'invalid ${path}',
- },
- })
|