0
0
Vueframework~3 mins

Why Computed in Composition API in Vue? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple formula can save you from endless manual updates and bugs!

The Scenario

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.

The Problem

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.

The Solution

Computed properties automatically update when their dependencies change. You just declare the formula once, and Vue keeps the value correct without extra work.

Before vs After
Before
let total = 0;
function updateTotal(items) {
  total = 0;
  for (const item of items) {
    total += item.price;
  }
}
After
const total = computed(() => items.value.reduce((sum, item) => sum + item.price, 0));
What It Enables

You can write clear, reactive code that always stays in sync with your data, making your app reliable and easier to maintain.

Real Life Example

In a shopping cart, computed properties keep the total price updated instantly as users add or remove products, without extra code to track changes.

Key Takeaways

Manual updates are error-prone and tedious.

Computed properties auto-update based on dependencies.

This leads to cleaner, more reliable reactive apps.