Bird
Raised Fist0
Vueframework~10 mins

Computed properties for derived state in Vue - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Computed properties for derived state
Define reactive state
↓
Create computed property
↓
Access computed property
↓
Computed property auto-updates
↓
UI reflects updated computed value
Start with reactive state, define a computed property based on it, then when state changes, computed updates automatically and UI shows new value.
Execution Sample
Vue
import { ref, computed } from 'vue'
const count = ref(1)
const double = computed(() => count.value * 2)
count.value = 3
console.log(double.value)
This code creates a reactive count, a computed double that doubles count, then updates count and logs the updated double.
Execution Table
StepActioncount.valuedouble.valueExplanation
1Initialize count with 112double computes 1 * 2 = 2
2Access double.value first time12Computed caches value 2
3Update count.value to 332double not recomputed yet, still cached 2
4Access double.value after count change36Computed recalculates 3 * 2 = 6
5Log double.value36Output is 6, reflecting updated count
💡 Execution ends after logging updated computed value reflecting reactive state change
Variable Tracker
VariableStartAfter Step 1After Step 3After Step 4Final
count.valueundefined1333
double.valueundefined2266
Key Moments - 2 Insights
Why does double.value not update immediately when count.value changes?
Because computed properties cache their value until accessed again. See step 3 and 4 in execution_table where double.value stays 2 until accessed after count changes.
What triggers the computed property to recalculate?
Accessing the computed property after its dependencies change triggers recalculation, as shown in step 4 where accessing double.value after count.value changed updates it.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is double.value at Step 3 after count.value changes but before double.value is accessed again?
A6
B3
C2
DUndefined
💡 Hint
Check the double.value column at Step 3 in the execution_table
At which step does double.value recalculate to reflect the new count.value?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look for when double.value changes from 2 to 6 in the execution_table
If count.value was updated to 5 instead of 3 at Step 3, what would double.value be at Step 4?
A10
B5
C6
D3
💡 Hint
Recall double.value is count.value * 2, see variable_tracker for pattern
Concept Snapshot
Computed properties in Vue automatically update when their reactive dependencies change.
They cache their value until accessed again.
Syntax: const comp = computed(() => reactiveVar.value * 2)
Access with comp.value to get latest derived state.
Useful for keeping UI in sync without manual updates.
Full Transcript
This example shows how Vue's computed properties work. We start with a reactive variable count initialized to 1. Then we define a computed property double that doubles count's value. Initially, double.value is 2. When we update count.value to 3, double.value does not change immediately because computed caches its value. Only when we access double.value again does it recalculate to 6. This automatic caching and recalculation keeps derived state efficient and reactive. The execution table traces each step, showing how count and double values change. Key points include understanding when computed recalculates and how caching works. This helps keep UI components updated automatically when underlying reactive data changes.

Practice

(1/5)
1. What is the main purpose of a computed property in Vue?
easy
A. To directly modify the DOM elements
B. To store static data that never changes
C. To create a value that updates automatically when its dependencies change
D. To replace methods for event handling

Solution

  1. Step 1: Understand computed property role

    Computed properties automatically update when their reactive dependencies change, unlike static data.
  2. Step 2: Compare with other options

    Static data does not update automatically, DOM manipulation is done differently, and event handling uses methods or event listeners.
  3. Final Answer:

    To create a value that updates automatically when its dependencies change -> Option C
  4. Quick Check:

    Computed properties = auto-updating values [OK]
Hint: Computed properties auto-update when data changes [OK]
Common Mistakes:
  • Thinking computed properties store static data
  • Confusing computed with methods for events
  • Assuming computed directly changes the DOM
2. Which of the following is the correct syntax to define a computed property named fullName using Vue's Composition API?
easy
A. const fullName = computed(() => firstName + ' ' + lastName)
B. const fullName = computed { return firstName + ' ' + lastName }
C. const fullName = computed(() => { firstName + ' ' + lastName })
D. const fullName = computed(() => firstName.concat(lastName))

Solution

  1. Step 1: Check correct computed syntax

    Vue's computed expects a function returning a value, so arrow function with parentheses and return expression is correct.
  2. Step 2: Analyze each option

    const fullName = computed(() => fullName + ' ' + lastName) uses arrow function returning concatenated string correctly. const fullName = computed { return firstName + ' ' + lastName } has wrong syntax (missing parentheses). const fullName = computed(() => { firstName + ' ' + lastName }) lacks return statement in block. const fullName = computed(() => firstName.concat(lastName)) uses concat without space.
  3. Final Answer:

    const fullName = computed(() => firstName + ' ' + lastName) -> Option A
  4. Quick Check:

    Correct computed syntax = const fullName = computed(() => firstName + ' ' + lastName) [OK]
Hint: Use arrow function with return expression inside computed [OK]
Common Mistakes:
  • Omitting parentheses in computed call
  • Forgetting return in block arrow function
  • Using string concat without space
3. Given the following Vue setup code, what will be the output of fullName.value?
import { ref, computed } from 'vue'
const firstName = ref('Jane')
const lastName = ref('Doe')
const fullName = computed(() => firstName.value + ' ' + lastName.value)

firstName.value = 'John'
medium
A. undefined
B. "Jane Doe"
C. "Jane John"
D. "John Doe"

Solution

  1. Step 1: Understand reactive refs and computed

    firstName and lastName are reactive refs. Changing firstName.value updates computed fullName automatically.
  2. Step 2: Evaluate fullName after update

    After setting firstName.value = 'John', fullName.value becomes 'John Doe' because computed uses current ref values.
  3. Final Answer:

    "John Doe" -> Option D
  4. Quick Check:

    Computed updates with ref changes = "John Doe" [OK]
Hint: Computed reflects latest ref values automatically [OK]
Common Mistakes:
  • Assuming computed keeps old value
  • Ignoring .value when accessing refs
  • Confusing variable names in output
4. Identify the error in this Vue computed property code:
import { ref, computed } from 'vue'
const count = ref(0)
const doubleCount = computed(() => {
  count + 2
})
medium
A. Missing return statement inside computed function
B. count should not be a ref
C. computed should be imported from 'vuex'
D. doubleCount should be a method, not computed

Solution

  1. Step 1: Check computed function body

    The arrow function uses braces but does not return a value explicitly, so it returns undefined.
  2. Step 2: Correct usage

    Either remove braces or add a return statement to return count.value + 2.
  3. Final Answer:

    Missing return statement inside computed function -> Option A
  4. Quick Check:

    Computed with braces needs return [OK]
Hint: Add return when using braces in arrow function [OK]
Common Mistakes:
  • Forgetting return in block arrow functions
  • Importing computed from wrong package
  • Misusing ref as normal variable
5. You have a list of products with prices and quantities as refs. How would you create a computed property totalPrice that sums the product of price and quantity for all products? Choose the correct computed property code snippet:
hard
A. const totalPrice = computed(() => products.reduce((sum, p) => sum + p.price * p.quantity, 0))
B. const totalPrice = computed(() => products.value.reduce((sum, p) => sum + p.price.value * p.quantity.value, 0))
C. const totalPrice = computed(() => { products.value.forEach(p => sum += p.price.value * p.quantity.value); return sum })
D. const totalPrice = computed(() => products.value.map(p => p.price.value * p.quantity.value))

Solution

  1. Step 1: Understand data structure and refs

    Each product has price and quantity as refs, so access with .value. products is a ref array, so use products.value.
  2. Step 2: Choose correct aggregation method

    Use reduce to sum all price * quantity values. const totalPrice = computed(() => products.value.reduce((sum, p) => sum + p.price.value * p.quantity.value, 0)) correctly uses reduce with .value access and initial sum 0.
  3. Step 3: Analyze incorrect options

    const totalPrice = computed(() => products.reduce((sum, p) => sum + p.price * p.quantity, 0)) misses .value on refs. const totalPrice = computed(() => { products.value.forEach(p => sum += p.price.value * p.quantity.value); return sum }) uses forEach but sum is undefined. const totalPrice = computed(() => products.value.map(p => p.price.value * p.quantity.value)) returns array, not sum.
  4. Final Answer:

    const totalPrice = computed(() => products.value.reduce((sum, p) => sum + p.price.value * p.quantity.value, 0)) -> Option B
  5. Quick Check:

    Use reduce with .value refs to sum totals [OK]
Hint: Use reduce with .value to sum reactive refs [OK]
Common Mistakes:
  • Forgetting .value on refs inside products
  • Using map instead of reduce for sum
  • Not initializing sum in reduce
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard