Two Way Data Binding in VueJS

Let’s learn about an important aspect of VueJS Programming i.e. Two Way Data Binding

Problem: You want to bind an input field to the VueJS Instance’s data property and also output the same property on your HTML page.

Solution: As opposed to plain javascript and jQuery library, it’s very simple to achieve two-way data binding with VueJS. In this example, we will create a simple HTML page to demonstrate two-way binding.

Consider the Vue Instance with just a single data property named name.

Livewire Component Library
    var app = new Vue({
        el: '#app',
        data: {
            name: "Kevin"
        }
    });

We have assigned it a default value Kevin, Let’s see how we can use this property to demonstrate two-way data binding.

Host Laravel Application on DigitalOcean

Use coupon 5balloons on this Cloudways Affiliate URL to get special discount.
    <div id="app">
        <h3>Your Name is : {{name}}</h3>
        <input type="text" v-model="name"/>
    </div> 

Notice the new directive v-model, we have used this directive to bind the value of text-box to the data property of our Vue Instance. Also, we have used the mustache brackets to display the value of the name property on the page.

Now as soon as you change the value of the text box, it changes the value of the underlying Vue data property, and via reactivity, it also changes the value of the displayed text.

Here is the full code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- development version, includes helpful console warnings -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <h3>Your Name is : {{name}}</h3>
        <input type="text" v-model="name"/>
    </div>
</body>
<script type="text/javascript">
    var app = new Vue({
        el: '#app',
        data: {
            name: "Kevin"
        }
    });
</script>
</html>

Output

Your Name is : {{name}}

Join my VueJS Newsletter

As I advance in my Journey of learning VueJS, I will be working on different exercises and challenges. Subscribe to receive the latest tutorials (every week) directly in your inbox.

    I won't send you spam. Unsubscribe at any time.

    Powered By ConvertKit

    Site Footer