0
0
Vueframework~3 mins

Computed vs method performance in Vue - When to Use Which

Choose your learning style9 modes available
The Big Idea

Discover how a small change can make your app feel lightning fast!

The Scenario

Imagine you have a webpage showing a list of items with prices, and you want to display the total price. You write a method to calculate the total every time the page updates.

The Problem

Calling the method repeatedly makes your page slow because it recalculates the total even when the prices haven't changed. This wastes time and makes the app feel laggy.

The Solution

Using computed properties, Vue automatically caches the total and only recalculates it when the prices actually change. This keeps your app fast and smooth without extra work.

Before vs After
Before
methods: { total() { return this.items.reduce((sum, i) => sum + i.price, 0); } }
After
computed: { total() { return this.items.reduce((sum, i) => sum + i.price, 0); } }
What It Enables

It enables efficient updates by recalculating values only when needed, making your app faster and more responsive.

Real Life Example

Think of a shopping cart that updates the total price instantly but only recalculates when you add or remove items, not every time you click elsewhere.

Key Takeaways

Methods recalculate on every call, which can slow down your app.

Computed properties cache results and update only when dependencies change.

Using computed properties improves performance and user experience.