How to handle form input in Vue
Handling form input effectively is crucial for creating interactive Vue applications with user data collection, validation, and form submission workflows.
As the creator of CoreUI, a widely used open-source UI library, I’ve implemented form input handling in numerous Vue components including login forms, user registration, and complex data entry interfaces in enterprise applications.
From my expertise, the most efficient approach is to use v-model
directive for two-way data binding.
This method provides reactive form state management, automatic value synchronization, and clean template syntax for various input types.
Use v-model
directive for two-way data binding between form inputs and component data.
<template>
<form @submit.prevent="handleSubmit">
<div>
<label>Name:</label>
<input v-model="user.name" type="text" required>
</div>
<div>
<label>Email:</label>
<input v-model="user.email" type="email" required>
</div>
<div>
<label>Age:</label>
<input v-model.number="user.age" type="number" min="18">
</div>
<div>
<label>Bio:</label>
<textarea v-model.trim="user.bio" rows="4"></textarea>
</div>
<div>
<label>
<input v-model="user.subscribed" type="checkbox">
Subscribe to newsletter
</label>
</div>
<button type="submit" :disabled="!isFormValid">Submit</button>
</form>
</template>
<script>
export default {
data() {
return {
user: {
name: '',
email: '',
age: null,
bio: '',
subscribed: false
}
}
},
computed: {
isFormValid() {
return this.user.name && this.user.email && this.user.age >= 18
}
},
methods: {
handleSubmit() {
if (this.isFormValid) {
console.log('Form submitted:', this.user)
// Handle form submission
}
}
}
}
</script>
The v-model
directive creates two-way data binding between form inputs and data properties. It automatically handles different input types: text, email, number, textarea, checkbox, and radio buttons. Use modifiers like .number
to convert string values to numbers, .trim
to remove whitespace, and .lazy
to sync on change instead of input. Vue reactively updates the data when users interact with inputs and updates inputs when data changes programmatically. This eliminates manual event handling for most form scenarios.
Best Practice Note:
This is the same approach we use in CoreUI Vue components for form handling and data collection. Use computed properties for form validation, implement proper error handling with validation libraries like Vuelidate or VeeValidate, and consider form submission states (loading, success, error) for better user experience.