VueJS Data Binding Example

We covered an example of Declarative Rendering in VueJS. Now let’s see how we can bind a data property to an input element via Vue JS.

Let’s directly dive into the example


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

    <div id="root">        
        <input type="text" v-model="message"><br/><br/>

        The value of input box is {{message}}<br/><br/>

        <button type="submit" onClick="app.message='Namaste'">Change Value</button>
    </div>

    <!-- development version, includes helpful console warnings -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>

        let app = new Vue({
            el: '#root',

            data: {
                message: "Hello World",
            }

        });
    </script>
    
</body>
</html>

As you can extending from the previous example. Here we have binded the value of message property to an input box via v-bind attribute. This is two-way binding.

Try changing the value of input box, it will also change the value we display below it. Also to demonstrate that we have a single point to truth. I have created a button which changes the value of message property on clicking the button.

Code

https://github.com/tushargugnani/vue-examples/blob/master/data-binding.html

Working Demo

https://tushargugnani.github.io/vue-examples/data-binding.html

tgugnani: Web Stuff Enthusiast.