Skip to content

Instantly share code, notes, and snippets.

@ronssij
Created November 30, 2023 05:51
Show Gist options
  • Save ronssij/06627b2497a7218726f97f36b5911c5b to your computer and use it in GitHub Desktop.
Save ronssij/06627b2497a7218726f97f36b5911c5b to your computer and use it in GitHub Desktop.
Vue3 Form Composables
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));
}
@ronssij
Copy link
Author

ronssij commented Nov 30, 2023

Instatiating Forms

const sectionForm = useForm(<ISectionForm>{
  name: null,
  image: null,
});

const sectionForm = useForm(<ISectionForm>{
  id: null,
  name: '',
  order: null,
  image: undefined,
  _method: 'PUT',
});

Setting, ressetting, clearing errors and setting form loading.

sectionForm.$setErrors(error.value?.data?.errors);
sectionForm.$reset();
sectionForm.$clearErrors();

sectionForm.$busy // true | false

sectionForm.$busy = false;

Getting and checking errors

sectionForm.$getError('name')
sectionForm.$hasError('name')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment