Computed properties can be used to do quick calculations of properties that are displayed in the view. These calculations will be cached and will only update when needed.
There are multiple ways in Vue to set values for the view. This includes directly binding data value to the view, using simple expressions or using filters to do simple transformations on the content. In addition to this, we can use computed properties to calculate display value based on a value or a set of values in the data model.
Computed properties allow us to have model-specific, complex values computed for the view. These values will be bound to the dependency values and only update when required.
For example, we can have an array of subject results in the data model:
data() {
return {
results: [
{
name: 'English',
marks: 70
},
{
name: 'Math',
marks: 80
},
{
name: 'History',
marks: 90
}
]
}
}
Assume that we want to view the total for all subjects. We can’t use filters or expressions for this task.
Here’s where computed properties come in handy. We can add a computed value to the model like this:
computed: {
totalMarks: function() {
let total = 0;
for(let i = 0; i < this.results.length; i++){
total += parseInt(this.results[i].marks);
}
return total;
}
}
The totalMarks
computed property calculates the total marks using the results
array. It simply loops through the values and returns the sub total.
We can then display the computed value in the view:
<div id="app">
<div v-for="subject in results">
<input v-model="subject.marks">
<span>
Marks for {{ subject.title }}: {{ subject.marks }}
</span>
</div>
<span>
Total marks are: {{ totalMarks }}
</span>
</div>
We could get the same result by using a method that outputs the total.
Instead of having the totalMarks
function in the computed section, we can move it to the methods and in the view we can change the template to execute the method:
<span>
Total marks are: {{ totalMarks() }}
</span>
While this gives the same output, we are taking a performance hit. Using this syntax, the totalMarks()
method gets executed every time the page renders (ie: with every change).
If instead we had a computed property, Vue remembers the values that the computed property is dependent on (ex: In the previous example, that would be results
). By doing so, Vue can calculate the values only if the dependency changes. Otherwise, the previously cached values will be returned.
Because of this, the function must be a pure function. It can’t have side-effects. The output must only be dependent on the values passed into the function.
By default, the computed properties only present a getter. But, it’s also possible to have setters.
computed: {
fullName: {
get: function() {
return this.firstName + this.lastName;
},
set: function(value) {
let names = value.split(' ');
this.firstName = names[0];
this.lastName = names[names.length - 1];
}
}
}
By having both getters and setters, we can bind the input value correctly to the model. If we set the fullName
in a method, the passed-in string will be split into the first and last name.
While computed properties may be sufficient in most cases, watchers provide an additional level of control by allowing us to listen for changes to a property.
Watchers, as the name suggests, allows us to watch for changes in a model object. While it’s possible to use watchers to get the same results as computed values, it’s often more complex and expensive.
We can use watchers for more complex requirements, for example:
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!