Vue 9: Computed Properties
easy⏱ 5 mincoursevue
Cached, derived state
A computed property derives a value from other reactive state and automatically re-runs only when its dependencies change — unlike a method, its result is cached between renders. In a real .vue file (Options API) it lives in the computed block; in Composition API you call computed(() => ...).
<!-- ProductCard.vue -->
<script>
export default {
props: ['price', 'qty'],
computed: {
total() {
return (this.price * this.qty).toFixed(2);
},
},
};
</script>
<template>
<p>Total: {{ '$' + total }}</p>
</template>
computed vs. a plain method
A method called from the template (total()) re-runs on every re-render of the component, no matter the reason. A computed property (total) only re-runs when price or qty actually change, returning the cached value otherwise — for expensive derivations, that difference matters a lot.
computed: {
total() { return this.price * this.qty; } // cached
},
methods: {
totalMethod() { return this.price * this.qty; } // recalculated every render
}
Build the invoice line
In data(), add price and qty. Add a computed total that multiplies them (formatted with .toFixed(2)), and a button that increments qty to see the computed value react.