Data Binding

What is data binding

As I mentioned in the previous chapter, data binding is the process that establishes a connection between the HTML and the Vue instance. In other words, in order to transfer the data to the Vue instance we need to bind HTML elements to Vue models. 

Luckily, Vue makes this process such a breeze.

Two-way binding (v-model)

In previous chapter's example, we bound the "message" inside the <p> using mustache-like syntax. That is called one-way binding. But what if the HTML element we're trying to bind to is an input? In such cases we use another Vue directive called the v-model.

Let's recreate the previous example:

new Vue({
el: '#app',
data: {
message: 'Hello VueJS students!'

But this time we bind the message also to an input:

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

As you can see, not only we get the "Hello VueJS students!" inside both <p> and <input>, but also we can change "message" by typing into the input. This is what I mean by "two-way binding". 

What's even cooler about this is that it happens in real-time as you type. 

When using v-model, you must initialize it in your Vue instance as the data. In case you don't want it to have any default value, then just set it to null or an empty string (""). 

Notice you did not have to set the "value" directive for the input. That's because v-model automatically does it for you.