Published on: 06 Jan, 2019

Data binding in Vue.js

Tumblr Digg Google Plus

In this tutorial, we are going to learn how to implement data binding in Vue.js. So what is exactly a data binding? A data binding means an interaction between user interface and a model property. For example of a model property can be an input field value. The interaction will start when a model property value get updated and the user interface will automatically renders the value of the model property.

Let's get started with the example tutorial on how the data binding works in Vue.js. We create the following html file with script tag of Vue.js library.

<!doctype html>
<html>
	<head>
		<title>Data Binding in Vue.js</title>
		<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
	</head>
<body>
	<div id="app">
		<div class="form-group">
			<label>What is your name?</label>
			<input type="text" v-model="myName"/>
		</div>
		<div class="form-group">
			<div>My Name is: {{ myName }}</div>
		</div>
	</div>

	<script>
		var app = new Vue({
		  el: '#app',
		  data: {
			myName: ''
		  }
		})
	</script>
</body>
</html>

If you see on the above code, we will have a text input and a label to display the data binding based on the input model property.

You can see the following demo in action.

Demo of Vue.js data binding.

My Name is: {{ myName }}
One thing you need to remember, once you use the directive v-model property, any initial attribute value such as checked attribute for radio button, selected attribute for dropdownlist or value attribute for input field will be completely ignored.

You can see the following example code. If I add the default value in the input value attribute, it will be just ignored.

<input type="text" v-model="myName" value="Andy"/>

Why it is ignored? The reason is the Vue.js app has overwritten the default attribute value with the predefined data variable called myName. So if you want to set a default value, you should set the default value under the data section in Vue.js. See the following example on how to set the default value in Vue.js.

var app = new Vue({
	el: '#app',
		data: {
		myName: 'Andy'
	}
})

If you have any question, feel free to post your comment below.

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.