Vue.Js Two Way Data Binding


Vue.Js Two Way Data Binding:- The mustache-style (double curly braces) binding we used in the previous example is a one-way binding. This means that it can only show the data of the model, not modify it. If you want to allow the view to edit the model you should create a two-way binding instead, using the v-model directive.


Vue.Js Two Way Data Binding | Example

In this tutorial we are going to create a simple example which tells us the basic difference between one way and two data binding. Let us understand two very important terms which will be used along with all tutorials.These two parts are main building blocks of Vue Framework.

  • 1. View – This contains the html UI parts which will be updated frequently as soon as the data model values are changed.
  • 2. View Model – This contains the data model part, this sits behind UI layer and exposes data needed by a View.

View

View Part contains the following code-

VueJs Example: View

<div id="my_view">

<label>Enter name:</label> <input id="name" name="name" type="text" />

{{ name }} is {{ rating }} nd rank holder.
</div>

View Model

View Model Part contains the following code-

VueJs Example: Model

var myModel = {
  name: "Vue.JS",
  rank:2
};

Vue Constructor | Example

Vue constructor is being created on each time the program loads and it has two parameters which takes information from view and model ; thus combines both to form a view model structure.

new Vue Instance | Example

new Vue({
  el: '#my_view',
  data:myModel
});

Complete Example | View-Model

The mustache-style binding we used in the previous example is a one-way binding. This means that it can only show the data of the model, not modify it. If you want to allow the view to edit the model you should create a two-way binding instead, using the v-model directive.

Note:- You can perform one time interpolation that means when you changes in data model there will be no change in view. We will do this by using v-once directive.

Example | Creating Two-Way Bindings

<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script>
<script>
var myModel= {name:"Vue.js",rank:2};
</script>
<body>
<div id="my_view">
<label>Enter name:</label> 
<input id="name" name="name" type="text" v-model="message"/>
{{ message }}
</div>
<script>
new Vue({
  el: '#my_view',
  data:{
         message: 'Hello Vue.Js!'
        }
})
</script>
</body>
</html>

Try it »

If you run the above example it will produce output something like this-


Advertisements

Add Comment

📖 Read More