Vue.js Computed Properties

Computed properties provide great value in development with Vue and are very similar to Methods in Vue.js, which we have already seen previously in the blog. However, there is a subtle difference which we will see today.
Properties in Vue.js are defined within the computed object just like a method is defined in the methods object. Let's see an example where we add two numbers with a method and with a computed property.
var app = new Vue({
el: "#app",
data: {
n1: 0,
n2: 0
},
computed: {
sum2: function () {
console.log('prop-> ' + this.n1 + '+' + this.n2);
return this.n1 + this.n2;
}
},
methods: {
sum: function () {
console.log('method-> ' + this.n1 + '+' + this.n2);
return this.n1 + this.n2;
}
}
});
Note that we have intentionally added a log to observe when the calculation is performed. However, the contents of the functions' methods are exactly the same. Now, to use this code, we could use the following HTML.
<div id="app">
Type the first number:
<input type="number" v-model.number="n1"><br />
Type the second number:
<input type="number" v-model.number="n2"><br />
The sum() is: {{ '\{\{ sum() \}\}' }}<br />
The sum2 is: {{ '\{\{ sum2 \}\}' }}
</div>
The result for the user with sum()
and sum2
will be exactly the same. At this point, you may have also noticed that there cannot be a computed property with the same name as a method since you could get unexpected results. You can try this example on codepen.
If you open the console in codepen, you will notice that the respective value is calculated when the numbers are changed.

So what is really the benefit of using a method over a computed property? The difference is in the cache. That's right, as you can see in the previous example, when one of the values n1 or n2 changes, both the property and the method calculate the value automatically. However, what happens when the property and method are called more than once? See the following:

As you can see, the call to the property did not generate a log, which means it was taken from the cache. Computed properties take the cached value as long as none of their reactive dependencies have changed.