What is computed()?
computed() is a function from the Composition API (Vue 3) that creates a computed property, a value that is automatically recalculated when its dependencies change, and cached until the dependencies change.
Put simply:
computed()is a reactive value that is computed from other reactive data and is "lazily" recalculated only when needed.
This is one of the most important tools in Vue.
How does computed() work?
import { ref, computed } from 'vue'
const count = ref(2)
const double = computed(() => count.value * 2)doubledepends oncount- Vue automatically tracks the dependency
- if
countchanges ->doubleis recalculated - if it does not change, Vue returns the cached value
The main difference between computed and a regular function
computed() is cached. A regular function is not.
Example:
const total = computed(() => expensiveCalculation())expensiveCalculation() will be called:
- once, until the dependent data changes
- after that the cache is returned
If this were just a function:
function total() {
return expensiveCalculation()
}it would be called every time the template renders.
Example in a component
<script setup>
import { ref, computed } from 'vue'
const price = ref(100)
const count = ref(3)
const total = computed(() => price.value * count.value)
</script>
<template>
<p>Total: {{ total }}</p>
</template>total updates automatically when price or count changes.
computed() can be writable (get + set)
const firstName = ref('Alex')
const lastName = ref('Smith')
const fullName = computed({
get() {
return `${firstName.value} ${lastName.value}`
},
set(newValue) {
[firstName.value, lastName.value] = newValue.split(' ')
}
})Usage:
fullName.value = "John Doe"When to use computed?
1. When a value depends on other values
price x quantity = total
2. For expensive calculations that should be cached
For example, sorting an array:
const sorted = computed(() => items.value.sort())3. When you need a "virtual" field based on data
For example formatting:
const formattedDate = computed(() => dayjs(date.value).format('DD.MM.YYYY'))4. For two-way values with get/set
For example, a fullName field composed of two parts.
When should you NOT use computed?
If you need to perform a side effect
That is what watch or watchEffect are for.
If the value should not be cached
If it needs to be recalculated on every render, a method is better.
computed vs watch (important for interviews)
| computed | watch |
|---|---|
| returns a value | watches a value |
| always synchronous | can be asynchronous |
| cached | not cached |
| for calculations | for side effects |
Summary (great for interviews)
computed()creates a computed reactive property that automatically updates when its dependencies change and is cached until the dependencies change. It is used for derived data, expensive calculations, and virtual fields. It can have get/set for two-way logic.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.