Computed properties
A computed property is a value derived from other data that Vue caches until something it depends on changes.
In this page:
Syntax
export default {
computed: {
computedName() {
return this.property * 2;
}
}
}
Computed properties
Define computed properties as functions that read reactive data and return a result. Vue tracks the dependencies and only recalculates when they change, unlike a method, which runs on every render. Writable computed properties use get and set.
Note:
Use computed for derived values and methods for actions.
Example: Computed properties
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<p>{{ first }} {{ last }} => {{ fullName }}</p>
<p>Total: {{ total }}</p>
</div>
<script>
let runs = 0;
Vue.createApp({
data() { return { first: "Ada", last: "Lovelace", prices: [10, 20, 30] }; },
computed: {
fullName() { return this.first + " " + this.last; },
total() { runs++; return this.prices.reduce((a, b) => a + b, 0); },
},
}).mount("#app");
console.log("total getter executed once for 2 renders of the same value:", runs === 1);
</script>
</body>
</html>
<!-- Output:
Rendered: Ada Lovelace => Ada LovelaceTotal: 60
console: total getter executed once for 2 renders of the same value: true
-->
Live Example
Related Topics
Common Mistakes
- Using methods for expensive derived values
- Causing side effects inside computed
- Mutating data inside a computed getter
Chapter Summary
- Computed values are derived and cached
- They recompute when dependencies change
- Methods run every call
- Avoid side effects in computed
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: