Vue 3 Reactive Form with Composition API
Build reactive forms in Vue 3 using the Composition API with ref and computed. Includes two-way binding, validation rules, dynamic field generation, and.
Code
import { ref, computed } from 'vue';
export function useForm(initialValues) {
const values = ref({ ...initialValues });
const errors = ref({});
const loading = ref(false);
const validate = (rules) => {
errors.value = {};
for (const [field, rule] of Object.entries(rules)) {
if (rule.required && !values.value[field]) {
errors.value[field] = rule.message;
}
}
return Object.keys(errors.value).length === 0;
};
const submit = async (onSubmit) => {
loading.value = true;
try { await onSubmit(values.value); }
finally { loading.value = false; }
};
return { values, errors, loading, validate, submit };
}How the snippet works
Vue 3 Reactive Form with Composition API is built around the functions validate, submit and useForm.
Iteration happens inside for (const [field, rule] of Object.entries(rules)) — everything outside it runs once. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. ref, computed are the only symbols borrowed from vue — the coupling is explicit and narrow.
The result comes back as an object carrying values, errors, loading, validate.
What to watch for
- Plan for an install step:
vueis a real dependency, resolved by the package manager.
Applying it
Entry signature: export function useForm(initialValues)
Import useForm from the file and call it — the rest of the code is implementation detail.
The call returns values, errors, loading, validate — destructure what you need at the call site.
Statements that matter
try { await onSubmit(values.value); }
return { values, errors, loading, validate, submit };
return Object.keys(errors.value).length === 0;
Interactive Tools for This Topic
FAQ
- Does `useForm` modify its input?
- The input survives unchanged; what you get back is a newly constructed value.
- Which packages must be installed first?
- Yes. The imports resolve to `vue`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.