What are computed properties?
Computed properties are values that are automatically recalculated when the data they depend on changes. They look like ordinary variables, but their value is always up to date and is cached for optimization.
In other words:
- computed properties are "smart variables" that update themselves when needed.
Simple example
<script setup>
import { ref, computed } from 'vue'
const firstName = ref("Tim")
const lastName = ref("Petrov")
// computed property
const fullName = computed(() => {
return firstName.value + " " + lastName.value
})
</script>
<template>
<p>{{ fullName }}</p>
</template>When firstName or lastName changes -> fullName recalculates automatically.
Key properties of computed
1) It recalculates automatically
If the dependencies changed, computed updates.
2) It is cached
If the dependencies haven't changed, Vue does not recalculate the value again.
This saves resources and makes the application faster.
Example
const double = computed(() => {
console.log("recalculating")
return count.value * 2
})If the UI accesses double 5 times but count has NOT changed, the log prints only once.
Computed vs methods
| What | computed | methods |
|---|---|---|
| Caching | Yes | No |
| Called | When dependencies change | Every time it renders |
| Usage | For derived state | For actions / logic |
Example where computed is better:
<p>{{ expensiveCalculation }}</p>If this were a method, it would run on every re-render, which is slow.
How are computed properties declared in the Composition API?
const sum = computed(() => a.value + b.value)In the Options API:
computed: {
sum() {
return this.a + this.b
}
}Two-way computed properties (getter + setter)
A computed property can have both a get and a set:
<script setup>
import { ref, computed } from 'vue'
const name = ref("Tim")
const formattedName = computed({
get() {
return name.value.toUpperCase()
},
set(newValue) {
name.value = newValue.toLowerCase()
}
})
</script>Usage:
<input v-model="formattedName" />When to use computed?
Use computed if:
- the value depends on other state
- it is derived state
- performance matters
- the value is needed in the template
Examples:
- a filtered list of products
- date formatting
- a computed item count
- full expressions instead of logic in the template
When not to use computed?
- when you need to perform an action (an API call, logic, side effects)
- when the value doesn't depend on reactive data
- when you don't need caching (use a method)
Summary (short)
Computed properties are reactive, cached properties that automatically recalculate when their dependencies change.
They:
- look like functions,
- but behave like variables,
- are optimized (cached),
- update automatically.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.