In-template expressions are incredibly convenient for simple calculations.
However, putting too much logic into your HTML templates makes them bloated and hard to maintain.
For complex logic that depends on reactive data, you should use Computed Properties.
A computed property is essentially a function that calculates a value based on other data variables.
You define them inside the computed object of your Vue instance.
They are used in your HTML templates exactly like normal data properties!
computed: {
publishedBooksMessage() {
return this.author.books.length > 0 ? 'Yes' : 'No'
}
}
You might be wondering, why use a computed property instead of a standard method?
The key difference lies in caching.
Computed properties are cached based on their reactive dependencies.
A computed property will only re-evaluate when its underlying data changes.
If the data hasn't changed, accessing the computed property returns the previously calculated result instantly.
A method, on the other hand, will execute its function every single time a re-render happens.
Using computed properties saves massive amounts of performance on heavy calculations.
computed: {
// This will NOT update unless reactive data changes
now() {
return Date.now()
}
}
Because Date.now() is not a reactive Vue dependency, this computed property will never update after its first calculation!
What is the primary architectural benefit of using a Computed Property over an inline expression?
What is the main functional difference between a Method and a Computed Property?