Discover how a simple formula can save you from endless manual updates and bugs!
Why Computed in Composition API in Vue? - Purpose & Use Cases
Imagine you have a list of items and you want to show the total price. Every time the list changes, you have to manually recalculate and update the total in your code.
Manually recalculating values is easy to forget and can cause bugs. If you miss updating the total, the displayed number becomes wrong and confuses users.
Computed properties automatically update when their dependencies change. You just declare the formula once, and Vue keeps the value correct without extra work.
let total = 0; function updateTotal(items) { total = 0; for (const item of items) { total += item.price; } }
const total = computed(() => items.value.reduce((sum, item) => sum + item.price, 0));You can write clear, reactive code that always stays in sync with your data, making your app reliable and easier to maintain.
In a shopping cart, computed properties keep the total price updated instantly as users add or remove products, without extra code to track changes.
Manual updates are error-prone and tedious.
Computed properties auto-update based on dependencies.
This leads to cleaner, more reliable reactive apps.