Vue Forms
Handling User Input with Forms:
In Vue. js, you can manage user input with the forms by using the v-model directive.
The v-model sets up a two-way link between the input elements and the Vue instance data, therefore, if there is a change in the input, the data will be updated and if there is a change in the data, then the input will be updated.
Therefore, it is simple to combine the form input with the application's state.
Example:
<div id="app">
<input type="text" v-model="message">
<p>You entered: {{ message }}</p>
</div>
<script>
new Vue({
el: '#app',
data: {
message: ''
}
});
</script>
Here, the input field value is tied to the message data property through v-model.
When the user inputs in the input field, the message data property is changed and the updated value is shown below the input field.
Form Validation:
Vue. js has various ways to implement form validation, for instance, it can be done by using the built-in HTML5 validation attributes, custom validation methods or even the third-party validation libraries.
You can employ computed properties or methods to verify the validity of form fields and display error messages in case of an invalid form input.
Example:
<div id="app">
<form @submit.prevent="submitForm">
<input type="email" v-model="email" required>
<span v-if="!isValidEmail">Please enter a valid email address.</span>
<button type="submit">Submit</button>
</form>
</div>
<script>
new Vue({
el: '#app',
data: {
email: ''
},
computed: {
isValidEmail() {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.email);
}
},
methods: {
submitForm() {
if (this.isValidEmail) {
// Form submission logic
console.log('Form submitted!');
} else {
// Display error message
console.log('Invalid email!');
}
}
}
});
</script>
This example includes a computed property isValidEmail, which is used to check if the entered email is valid.
Should the email be invalid, we show an error message below the input field.
Once, the form is submitted, we recheck the validity of the email and perform the form submission logic accordingly.
Two-Way Data Binding with v-model:
V-model gives the two-way data binding of the form input elements and Vue instance data, as I have stated earlier.
This implies that the modifications done on the input element by the user are reflected immediately in the Vue instance data, and the changes in the Vue instance data are immediately reflected in the input element.
Example:
<div id="app">
<input type="text" v-model="message">
<p>You entered: {{ message }}</p>
</div>
<script>
new Vue({
el: '#app',
data: {
message: ''
}
});
</script>
In this case, any modifications made to the input field by the user are immediately shown in the message data property, and vice versa, any modifications in the message data property are immediately reflected in the input field.
This makes it sure that the form input is in sync with the Vue instance data.