Vue is an amazing front-end javascript framework that allows you to create some awesome applications. One of the simplest features of Vue is the 2-way databinding. Two-way data binding will allow you to map a variable to an HTML Dom element. When that variable is updated, it will automatically update the DOM as well.
Before you can see this in action we'll need to include VueJS in a simple project. We can use the Vue CDN link and include it in our page like so:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>VueJS 2-way data binding</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</body>
</html>
Now, that we've included the CDN link in our page, the next step is to create a simple Vue instance with some data:
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
You can see in the code above that we are creating a new Vue instance and attaching it to an element with an id of #app
. Let's include that in our HTML file, the final result will look like so:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>VueJS 2-way data binding</title>
</head>
<body>
<div id="app">
{{ message }}
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
});
</script>
</body>
</html>
You'll see that from the code above we've just included {{ message }}
inside of our app
element. The value of message
will automatically update when the message
variable is updated from our data
object inside of our Vue instance.
In order to see this in action we'll bind
the message
variable to an input
, like so:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>VueJS 2-way data binding</title>
</head>
<body>
<div id="app">
{{ message }}
<input type="text" v-model="message">
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
});
</script>
</body>
</html>
You can see a live preview of this functionality from the codepen below:
That's pretty much it! Two-way data binding will make your life a lot easier as a developer and it will also make building real-time applications easier and quicker than ever before.
Cheers!
Comments (0)