Computed Properties in VueJS
Let’s now go ahead and learn a new concept in VueJS, Computed Properties.
Problem: We want to manipulate the data property of Vue Instance for the presentation purpose.
Solution:
Let’s build a simple application which has an input box, wherein user can type their name and we show the count of characters in the name in the realtime.
Something like the image below.
Use coupon 5balloons on this Cloudways Affiliate URL to get special discount.
To build this app we have the following HTML
<div id="app">
<label>Type your name: </label>
<input type="text" v-model="name"/> <br/><br/>
Your name is {{name}}<br/>
And is {{charcount}} characters long.
</div>
In the above HTML, we have an input box that is attached to the name data property of the Vue Instance. Below the text box, we are displaying the name along with the character length of the name.
Let’s see how we can make use of Computed properties to display the character length count.
var app = new Vue({
el: '#app',
data: {
name: '',
},
computed: {
charcount: function () {
return this.name.length;
}
}
});
In the above code snippet we have a Vue Instance with a single data property named name
, along with that we have defined a new object named computed
.
Inside this object you can define all the computed properties, In this example we have defined a computed property named charcount
, which is dependent on the name
data property, and we have to refer that via this
keyword.
Computed properties have the ability to re-render themselves when the data that they are dependent on changes, thus as we type the name in the text-box we can see the character length changing in real-time.
This example is very basic, but computed properties are a very powerful tool for encapsulating data manipulations and transformations that stay synced with the data that they refer to.
Demo
Your name is {{name}}
And is {{charcount}} characters long.