Computed Properties

Loading concept...

Vue.js Computed Properties: Your Smart Kitchen Helper 🍳

The Magic of Automatic Cooking

Imagine you have a magical kitchen helper. You put ingredients on the counter, and this helper automatically makes the dish—without you asking every time!

That’s exactly what Computed Properties do in Vue.js. They watch your ingredients (data), and whenever something changes, they automatically cook up the result.


🎯 What Are Computed Properties?

Think of computed properties like a smart calculator on your desk.

Regular Data = Numbers you write down Computed Property = Calculator that adds them automatically

<script setup>
import { ref, computed } from 'vue'

const firstName = ref('Spider')
const lastName = ref('Man')

// The smart calculator!
const fullName = computed(() => {
  return firstName.value + ' ' + lastName.value
})
</script>

<template>
  <p>{{ fullName }}</p>
  <!-- Shows: Spider Man -->
</template>

What just happened?

  • We have two ingredients: firstName and lastName
  • The computed property watches both
  • Whenever either changes, fullName updates automatically!

Why Not Just Use a Method?

Good question! Here’s the difference:

Method Computed
Runs every time you call it Runs only when data changes
Like cooking fresh each time Like reheating only if recipe changed
No memory Remembers the result

đź“– Story Time: The Lazy-Smart Student

Meet Computed Carl. He’s in math class.

The teacher asks: “What is 5 + 3?”

Regular Reggie (methods) calculates: 5 + 3 = 8. âś…

Teacher asks again: “What is 5 + 3?”

Regular Reggie calculates again: 5 + 3 = 8. (Works hard!)

Computed Carl says: “I already know it’s 8. The numbers didn’t change!” (Works smart!)

Teacher changes the question: “Now what is 5 + 4?”

Computed Carl notices the change and calculates: 5 + 4 = 9. âś…

This is Computed Caching in action!


🔄 Computed Caching: The Memory Superpower

Computed properties have a superpower: they remember their answer!

const items = ref([
  { name: 'Apple', price: 1 },
  { name: 'Banana', price: 2 },
  { name: 'Orange', price: 3 }
])

const totalPrice = computed(() => {
  console.log('Calculating...')
  return items.value.reduce(
    (sum, item) => sum + item.price, 0
  )
})

First time you use totalPrice:

  • Console shows: “Calculating…”
  • Result: 6

Second time (nothing changed):

  • Console shows: nothing! (Used cached result)
  • Result: 6 (instant!)

When items change:

  • Console shows: “Calculating…”
  • New result appears!

đź§  How Caching Works (Simple Version)

graph TD A["You ask for computed value"] --> B{Did dependencies change?} B -->|No| C["Return cached value ⚡"] B -->|Yes| D["Recalculate"] D --> E["Store new result"] E --> F["Return new value"]

✏️ Writable Computed: Two-Way Magic

Most computed properties are read-only. You can look, but you can’t change.

But sometimes you want a two-way mirror!

The Pizza Order Example

Imagine ordering pizza:

  • You say “I want 3 pizzas”
  • The shop says “That’s $30”

But what if you say:

  • “I have $45”
  • The shop says “That’s 4.5 pizzas… so 4 pizzas!”

This is a writable computed!

const pricePerPizza = 10

const pizzaCount = ref(3)

const totalCost = computed({
  // Reading: pizzas → money
  get() {
    return pizzaCount.value * pricePerPizza
  },
  // Writing: money → pizzas
  set(newTotal) {
    pizzaCount.value = Math.floor(
      newTotal / pricePerPizza
    )
  }
})

// Usage:
console.log(totalCost.value) // 30

totalCost.value = 45 // Setting!
console.log(pizzaCount.value) // 4

When to Use Writable Computed?

âś… Good uses:

  • Converting between units (Celsius ↔ Fahrenheit)
  • Form inputs that need formatting
  • Two-way binding with transformations

❌ Avoid when:

  • Simple value storage (just use ref)
  • Complex logic (can get confusing)

🏆 Computed Best Practices

Rule 1: Keep It Pure

Computed properties should be like a math formula:

  • Same input = Same output
  • No surprises!
// âś… GOOD - Pure function
const doubled = computed(() => {
  return count.value * 2
})

// ❌ BAD - Side effects
const doubled = computed(() => {
  console.log('Calculated!') // Side effect!
  someOtherValue.value = 10  // Changing stuff!
  return count.value * 2
})

Rule 2: Don’t Mutate Inside

Never change your ingredients while cooking!

// ❌ BAD - Mutating inside computed
const sortedList = computed(() => {
  return items.value.sort() // Mutates original!
})

// âś… GOOD - Create a copy first
const sortedList = computed(() => {
  return [...items.value].sort() // Safe copy!
})

Rule 3: Use Computed, Not Methods, for Display

If it’s used in the template for display:

<!-- ❌ Method - recalculates every render -->
<p>{{ getFullName() }}</p>

<!-- âś… Computed - caches the result -->
<p>{{ fullName }}</p>

Rule 4: Avoid Expensive Operations Without Care

Computed recalculates when dependencies change. If the operation is slow, consider:

// For very expensive operations
const expensiveResult = computed(() => {
  // This runs when ANY dependency changes
  return heavyCalculation(data.value)
})

Rule 5: Name It Like a Value, Not an Action

// ❌ Sounds like a function
const calculateTotal = computed(...)

// âś… Sounds like a value
const total = computed(...)
const formattedDate = computed(...)
const isVisible = computed(...)

🎪 Putting It All Together

Here’s a complete example showing all concepts:

<script setup>
import { ref, computed } from 'vue'

// Our data (ingredients)
const items = ref([
  { name: 'Sword', price: 100 },
  { name: 'Shield', price: 80 },
  { name: 'Potion', price: 20 }
])
const taxRate = ref(0.1)

// Computed: total before tax (cached!)
const subtotal = computed(() => {
  return items.value.reduce(
    (sum, item) => sum + item.price, 0
  )
})

// Computed: final total
const total = computed(() => {
  return subtotal.value * (1 + taxRate.value)
})

// Writable computed: budget control
const budget = computed({
  get() {
    return total.value
  },
  set(newBudget) {
    // Adjust tax to fit budget
    taxRate.value =
      (newBudget / subtotal.value) - 1
  }
})
</script>

🌟 Quick Summary

Concept What It Does Remember
Computed Auto-calculates from data Like a smart calculator
Caching Remembers until data changes Like a lazy-smart student
Writable Two-way transformation Like currency exchange
Best Practices Keep pure, no mutations Like a math formula

🎉 You Did It!

Now you understand Vue.js Computed Properties like a pro!

Remember:

  • Computed = Automatic calculations
  • Caching = Smart memory
  • Writable = Two-way street
  • Best Practices = Keep it clean and pure

Go build something amazing! 🚀

Loading story...

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Stay Tuned!

Interactive content is coming soon.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Stay Tuned!

Cheatsheet is coming soon.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Stay Tuned!

Quiz is coming soon.

Flashcard Preview

Flashcard - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Stay Tuned!

Flashcards are coming soon.