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.
Note: Remember Computed properties should not be used for changing the original data, while methods can be used to change data. Computation properties can be used to change the presentation of existing data.
[WP-Coder id="9"]