What are computed properties?
Computed properties are values that are automatically recalculated when their dependencies change, and cached until those dependencies change.
In simpler terms:
A computed property is a value calculated from other reactive data that updates automatically, without recalculating unnecessarily.
This is one of the key reactivity tools in Vue.
Example of a computed property (Options API)
computed: {
double() {
return this.count * 2
}
}If this.count changes, Vue recalculates double.
If not, it returns the cached value.
Example of a computed property (Composition API)
import { ref, computed } from 'vue'
const count = ref(2)
const double = computed(() => count.value * 2)The main difference between computed and methods
methods are called every time, on every render
computed is called only when its dependencies change (cached)
Example:
<p>{{ heavyCalculation() }}</p> <!-- called every time -->
<p>{{ heavyValue }}</p> <!-- cached -->heavyValue is computed:
const heavyValue = computed(() => heavyCalculation())When should you use computed properties?
1. When a value depends on other reactive data
For example:
- an order total:
price * quantity - filtering a list
- formatting data
- converting strings/dates
2. To cache the results of expensive operations
For example, sorting:
const sorted = computed(() => list.value.sort())3. When you need a "virtual property" of an object
For example:
fullName = firstName + " " + lastNameComputed with a getter/setter
Computed properties can be two-way:
const fullName = computed({
get() {
return firstName.value + " " + lastName.value
},
set(value) {
[firstName.value, lastName.value] = value.split(" ")
}
})Usage:
fullName.value = "John Doe"How does computed work under the hood?
- Vue tracks the dependencies used inside the function.
- If any dependency changes → computed is recalculated.
- If not → the cached value is returned.
When should you NOT use computed?
When you need to perform an action (side effect)
Then you need watch.
When you need to call a function with arguments
Computed does not accept arguments, so use a method instead.
Summary (ideal for an interview)
Computed properties are reactive values that automatically recalculate when their dependencies change and are cached until the next change. They are used for derived values, optimizing calculations, and creating virtual properties. Vue has computed in the Options API and the computed() function in the Composition API.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.