Two way binding in Vue.js

Vue.js is a JavaScript framework getting popular considering its simplicity praised a lot these days. There are a lot of JavaScript frameworks among which React and Angular are popular among web developers. Vue.js is much flexible and less opinionated framework than Angular. It’s similar to React but much simpler. Vue.js supports Two-way binding. That is it keeps your data in sync with your DOM without you having to do anything. Two-way binding in Vue.js is MVVM pattern. That is Model View View Model. Like MVC, Model is the data object and view is what is displayed up. The Model can tie to the View and the View can tie back to Model. In one way binding, JS variable is bound to the DOM.

<div id="app">
  <span>The message is: {{message}}</span>
</div>
new Vue({
 el: '#app',
 data: {
   message: 'vue js one way binding'
 }
});
Here when you change the data in JS, it will also update in the DOM. So you will get the updated message on the page. You can get the basic code here. But in two way binding, Js variable can be bound to the DOM and data is also bound from the DOM back to JS.
<div id="app">
  <span>{{message}}</span><br>
  <input v-model="message">
</div>
new Vue({
  el: '#app',
  data: {
    message: 'vue js two way binding'
  }
});
Now, if you type anything into your input, your JS variable is updated with the change, which in turn updates your span. You can get the code here.

Directive

The attribute used with input v-modelis a vue directive. We have to assign data model with the directive. A directive’s job is to reactively apply special behavior to the DOM when the value of its expression changes. In the case of v-model, it binds the element to one of the data properties that Vue is watching. Vue has many directives. Another one is v-on which binds an element to an event. For example, v-on: click  is to bind element when clicking on it. Working with html forms is a breeze in Vue. This is where two-way binding shines. It does not bring any issues  even in complex cases, though watchers may remind of Angular 1 at first glance. One-way flow with callback passing is always at your service when you do your components splitting.

Two way binding with JQuery

You can also do two-way binding in jquery or plain JS. But you have to use some event listeners when there occurs any change in the input. You have to make your own logic to update DOM when there are any changes in the elements. You can see the example here. You can achieve reactive data binding in jQuery, but it’s just a sideshow. In Vue, it’s the main event. Hope you will try it. Happy Coding!

Reference

https://vuejs.org/ https://vuejs.org/v2/guide/forms.html https://www.youtube.com/watch?v=nEdsu6heW9o]]>