How to Build Vue 3 Reactive Forms
Introduction
Vue 3’s Composition API provides a clean, reusable way to build reactive forms. This tutorial shows how to create a form composable with validation and submission.
Step 1: Create a useForm Composable
import { ref, computed } from "vue";
export function useForm(initialValues) {
const values = ref({ ...initialValues });
const errors = ref({});
const loading = ref(false);
const reset = () => {
values.value = { ...initialValues };
errors.value = {};
};
return { values, errors, loading, reset };
}
Step 2: Add Validation
export function useForm(initialValues, rules) {
const values = ref({ ...initialValues });
const errors = computed(() => {
const e = {};
for (const [field, validate] of Object.entries(rules)) {
const result = validate(values.value[field]);
if (result !== true) e[field] = result;
}
return e;
});
const isValid = computed(() => Object.keys(errors.value).length === 0);
return { values, errors, isValid };
}
Step 3: Handle Submission
<script setup>
const { values, errors, isValid } = useForm(
{ email: "", password: "" },
{
email: (v) => v.includes("@") || "Invalid email",
password: (v) => v.length >= 8 || "Min 8 characters",
}
);
const submit = async () => {
if (!isValid.value) return;
loading.value = true;
try {
await api.login(values.value);
} finally {
loading.value = false;
}
};
</script>
Conclusion
Vue 3 composables provide a powerful pattern for form management. The reactive system automatically updates errors and validity as the user types, creating a smooth, responsive form experience.