Course Content
VUE Tutorial
About Lesson

v-model for Two-Way Binding

Vue.js is a powerful JavaScript framework that simplifies the development of dynamic web applications. One of its key features is the ability to perform two-way data binding, which significantly enhances the way data is managed and updated in your application. In this post, we’ll delve into the concept of two-way binding in Vue.js, specifically focusing on the v-model directive.

What is Two-Way Binding?

Two-way binding is a mechanism that allows the synchronization of data between the user interface and the underlying data model. In Vue.js, this is achieved through the v-model directive. With two-way binding, changes made in the user interface automatically update the data model, and vice versa.

Getting Started with v-model

Installation and Setup

Before diving into the details, ensure you have Vue.js installed in your project. You can include it via CDN or use a package manager like npm.

<!-- Include Vue.js via CDN -->
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
Basic Syntax

The v-model directive is typically used with form elements, such as input, textarea, and select. It creates a two-way binding on the specified data property. Here’s a basic example:

<div id="app">
<input v-model="message">
<p>Message: {{ message }}</p>
</div>

<script>
new Vue({
el: '#app',
data: {
message: ''
}
});
</script>

In this example, the message the data property is bound to the input field. Any changes made in the input field will be reflected in the paragraph below it.

Custom Components and V-model

Vue.js also allows you to use v-model with custom components. This feature is particularly useful when building complex forms or reusable components. Let’s explore a simple custom input component:

CustomInput.vue
<template>
<input :value="value" @input="$emit('input', $event)">
</template>

<script>
export default {
props: ['value'] };
</script>

Using Custom Input Component
<div id="app">
<custom-input v-model="customMessage"></custom-input>
<p>Custom Message: {{ customMessage }}</p>
</div>

<script>
import CustomInput from './CustomInput.vue';

new Vue({
el: '#app',
components: {
CustomInput
},
data: {
customMessage: ''
}
});
</script>

In this example, the CustomInput the component is bound to the customMessage data property using v-model.

Form Validation with v-model

Vue.js simplifies form validation by integrating v-model with validation logic. You can use computed properties or watchers to perform real-time validation as the user interacts with the form.