0
0
Vueframework~15 mins

Computed in Composition API in Vue - Deep Dive

Choose your learning style9 modes available
Overview - Computed in Composition API
What is it?
Computed properties in the Composition API are special reactive values that automatically update when their dependencies change. They let you define logic that depends on other reactive data, and Vue keeps the computed value fresh without extra work. This helps keep your code clean and efficient by avoiding manual updates.
Why it matters
Without computed properties, you would have to manually track and update values whenever their dependencies change, which is error-prone and tedious. Computed properties solve this by automatically recalculating only when needed, improving performance and making your app more reliable and easier to maintain.
Where it fits
Before learning computed properties, you should understand Vue's reactivity system and how to use reactive and ref to create reactive data. After mastering computed, you can explore watchers for side effects and advanced state management patterns.
Mental Model
Core Idea
A computed property is a smart value that watches its reactive inputs and updates itself automatically only when those inputs change.
Think of it like...
It's like a smart thermostat that adjusts the room temperature automatically based on the current temperature and your settings, without you needing to keep changing it manually.
┌───────────────┐
│ Reactive Data │
└──────┬────────┘
       │ changes
       ▼
┌─────────────────────┐
│ Computed Property    │
│ (auto recalculates)  │
└─────────┬───────────┘
          │ used by
          ▼
┌─────────────────────┐
│ Template or Logic   │
└─────────────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding reactive and ref basics
🤔
Concept: Learn how Vue tracks reactive data using ref and reactive to create reactive variables.
In Vue's Composition API, you create reactive data using ref() for primitive values and reactive() for objects. These functions wrap your data so Vue can track changes and update the UI automatically. Example: const count = ref(0) const state = reactive({ name: 'Vue' })
Result
count and state become reactive, so when their values change, Vue knows to update anything that uses them.
Understanding reactive and ref is essential because computed properties depend on these reactive sources to know when to update.
2
FoundationIntroducing computed properties
🤔
Concept: Computed properties are functions that return a value derived from reactive data and update automatically when dependencies change.
You create a computed property by passing a getter function to Vue's computed() function. Vue tracks which reactive values the getter uses and recalculates the computed value only when those change. Example: const count = ref(1) const double = computed(() => count.value * 2)
Result
double.value will always be twice the current count.value, updating automatically when count changes.
Computed properties let you write derived state declaratively, avoiding manual updates and keeping your code clean.
3
IntermediateUsing computed in templates and logic
🤔
Concept: Learn how to use computed properties both inside your component logic and directly in templates.
In the template, you can use computed properties just like reactive data. In the script, access the computed value with .value. Example template:

{{ double }}

Example script: console.log(double.value)
Result
The UI and logic always see the latest computed value without extra code.
Knowing how to use computed properties in both places helps you write flexible and maintainable components.
4
IntermediateComputed with getters and setters
🤔
Concept: Computed properties can have both a getter and a setter to allow two-way binding and controlled updates.
You can define a computed property with an object containing get and set functions. Example: const name = ref('Alice') const fullName = computed({ get: () => name.value + ' Smith', set: val => { name.value = val.split(' ')[0] } })
Result
fullName.value returns 'Alice Smith', and setting fullName.value updates name.value accordingly.
Using setters in computed properties enables reactive two-way data flows, useful for form inputs and complex state.
5
IntermediateComputed caching and performance
🤔Before reading on: do you think computed properties recalculate every time they are accessed, or only when dependencies change? Commit to your answer.
Concept: Computed properties cache their results and only recompute when their reactive dependencies change, improving performance.
When you access a computed property multiple times without changing its dependencies, Vue returns the cached value instantly. It recalculates only when a dependency changes. This avoids unnecessary work and keeps your app fast.
Result
Repeated access to computed.value is efficient and does not cause extra recalculations.
Understanding caching explains why computed properties are more efficient than methods for derived state.
6
AdvancedComputed vs methods and watchers
🤔Before reading on: do you think computed properties and methods behave the same way in templates? Commit to your answer.
Concept: Computed properties cache results and update reactively, while methods run fresh every time and watchers react to changes for side effects.
Methods are functions called on each template render, so they do not cache results. Computed properties cache and update only when needed. Watchers run code in response to reactive changes but don't produce values for templates. Use computed for derived state, methods for actions, and watchers for side effects.
Result
Choosing the right tool improves app performance and clarity.
Knowing these differences helps avoid bugs and inefficient code in Vue apps.
7
ExpertReactivity tracking internals in computed
🤔Before reading on: do you think Vue tracks dependencies of computed properties eagerly or lazily? Commit to your answer.
Concept: Vue tracks dependencies lazily when the computed property is accessed, using a dependency tracking system to know exactly which reactive sources to watch.
When you first access a computed property, Vue runs its getter and records which reactive refs or reactive objects it reads. It then subscribes to changes only on those dependencies. If dependencies change, Vue marks the computed as dirty to recalculate on next access. This lazy tracking avoids overhead when computed properties are unused.
Result
Computed properties update efficiently and only when necessary, even in complex apps.
Understanding lazy dependency tracking explains why unused computed properties don't slow down your app.
Under the Hood
Computed properties use Vue's reactive effect system. When a computed getter runs, Vue records all reactive dependencies accessed. It creates a reactive effect that tracks these dependencies. When any dependency changes, Vue marks the computed property as dirty but does not recalculate immediately. On next access, it recalculates and caches the new value. This lazy evaluation and caching optimize performance and ensure consistency.
Why designed this way?
Vue's computed properties were designed to minimize unnecessary recalculations and improve app responsiveness. Early reactive systems recalculated eagerly, causing performance issues. Vue chose lazy tracking and caching to balance reactivity with efficiency. Alternatives like manual watchers or methods were less declarative and more error-prone.
┌───────────────┐
│ Computed Prop │
│   (getter)    │
└──────┬────────┘
       │ runs
       ▼
┌───────────────┐
│ Dependency    │
│ Tracking      │
└──────┬────────┘
       │ subscribes
       ▼
┌───────────────┐
│ Reactive Data │
│ (ref/reactive)│
└───────────────┘
       ▲
       │ changes
       └─────────────┐
                     ▼
             ┌───────────────┐
             │ Mark Dirty    │
             │ (lazy update) │
             └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do computed properties always recalculate every time you access them? Commit to yes or no.
Common Belief:Computed properties recalculate their value every time you access them.
Tap to reveal reality
Reality:Computed properties cache their value and only recalculate when one of their reactive dependencies changes.
Why it matters:Believing they recalculate every time leads to unnecessary performance worries and misuse of methods instead of computed.
Quick: Can you assign a new value directly to a computed property without a setter? Commit to yes or no.
Common Belief:You can always assign a new value to a computed property like a normal variable.
Tap to reveal reality
Reality:Computed properties without a setter are read-only; assigning to them causes errors.
Why it matters:Trying to assign to a read-only computed causes runtime errors and confusion.
Quick: Are computed properties and watchers interchangeable for updating UI? Commit to yes or no.
Common Belief:Computed properties and watchers do the same thing and can be used interchangeably.
Tap to reveal reality
Reality:Computed properties produce reactive values for templates, while watchers run side effects and do not produce values.
Why it matters:Misusing watchers instead of computed leads to more complex and less efficient code.
Quick: Does Vue track dependencies of computed properties eagerly when the component loads? Commit to yes or no.
Common Belief:Vue tracks all dependencies of computed properties eagerly as soon as the component loads.
Tap to reveal reality
Reality:Vue tracks dependencies lazily when the computed property is first accessed, not before.
Why it matters:Assuming eager tracking can lead to misunderstandings about performance and when computed properties update.
Expert Zone
1
Computed properties can be chained, where one computed depends on another, and Vue efficiently tracks all dependencies across the chain.
2
Using setters in computed properties allows for controlled two-way data binding, but improper setters can cause infinite loops if they update dependencies incorrectly.
3
Computed properties are lazy by default but can be forced to evaluate eagerly by accessing their value early, which can be useful in some performance tuning scenarios.
When NOT to use
Avoid using computed properties when you need to perform side effects or asynchronous operations; use watchers or methods instead. Also, for simple one-time calculations that don't depend on reactive data, plain functions are better.
Production Patterns
In real-world Vue apps, computed properties are widely used for filtering lists, formatting data, and combining multiple reactive sources. They are often paired with Vuex or Pinia stores to derive state efficiently. Experts also use computed properties to memoize expensive calculations and avoid unnecessary DOM updates.
Connections
Memoization in Functional Programming
Computed properties implement a form of memoization by caching results based on inputs.
Understanding computed as memoized functions helps grasp why they improve performance by avoiding repeated work.
Spreadsheet Formulas
Computed properties are like spreadsheet cells that automatically update when referenced cells change.
This connection clarifies how reactive dependencies propagate changes automatically, just like formulas recalculate in spreadsheets.
Observer Pattern in Software Design
Computed properties use the observer pattern to watch reactive data and update dependents.
Recognizing computed as an observer pattern instance helps understand its event-driven update mechanism.
Common Pitfalls
#1Trying to assign a value to a computed property without a setter.
Wrong approach:const double = computed(() => count.value * 2) double.value = 10 // error: computed is read-only
Correct approach:const double = computed({ get: () => count.value * 2, set: val => { count.value = val / 2 } }) double.value = 10 // works correctly
Root cause:Misunderstanding that computed properties without setters are read-only reactive values.
#2Using methods instead of computed for derived reactive state.
Wrong approach:const double = () => count.value * 2 // used in template as {{ double() }}
Correct approach:const double = computed(() => count.value * 2) // used in template as {{ double }}
Root cause:Not realizing methods run fresh every render and do not cache results, causing performance issues.
#3Performing side effects inside computed getters.
Wrong approach:const double = computed(() => { console.log('Calculating') return count.value * 2 })
Correct approach:const double = computed(() => count.value * 2) watch(count, () => { console.log('Count changed') })
Root cause:Confusing computed properties as places for side effects instead of pure derived state.
Key Takeaways
Computed properties in Vue's Composition API are reactive values that automatically update when their dependencies change, using caching for efficiency.
They are created with the computed() function and can have getters and optional setters for two-way binding.
Computed properties differ from methods and watchers in caching behavior and purpose, making them ideal for derived state.
Vue tracks dependencies lazily when computed properties are accessed, optimizing performance by avoiding unnecessary recalculations.
Avoid side effects in computed getters and use watchers for reacting to changes with side effects.