Created
November 30, 2023 05:51
-
-
Save ronssij/06627b2497a7218726f97f36b5911c5b to your computer and use it in GitHub Desktop.
Vue3 Form Composables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const form = <TFormData>(formData: TFormData) => { | |
const $originalData = useCloneDeep(formData) as object; | |
const $errors = ref({}); | |
const $busy = ref(false); | |
let _data = formData as object; | |
const $setErrors = <TErrors>(errors: object | TErrors) => { | |
return ($errors.value = errors || {}); | |
}; | |
const $clearErrors = () => { | |
return ($errors.value = {} as object); | |
}; | |
const $hasError = (field: string): boolean => { | |
return useIncludes($errors.value, field); | |
}; | |
const $getError = (field: string): string => { | |
return useGet($errors.value, field); | |
}; | |
const $mimeTypeOf = (mime: string, value: string = 'image'): boolean => { | |
return useFirst(useSplit(mime, '/')) === value; | |
}; | |
return { | |
...formData, | |
$originalData, | |
$errors, | |
$busy, | |
$data() { | |
useEach(_data, (_, key) => useSet(_data, key, useGet(this, key))) | |
return _data; | |
}, | |
$reset() { | |
useEach($originalData, (value, key) => useSet(this as any, key, value)) | |
$clearErrors(); | |
}, | |
$hasError, | |
$setErrors, | |
$clearErrors, | |
$getError, | |
$mimeTypeOf, | |
}; | |
}; | |
export function useForm<TFormData>(data: TFormData) { | |
return reactive(form(data)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Instatiating Forms
Setting, ressetting, clearing errors and setting form loading.
Getting and checking errors