Skip to main content

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

javascript
<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

javascript
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

Whatcomputedmethods
CachingYesNo
CalledWhen dependencies changeEvery time it renders
UsageFor derived stateFor actions / logic

Example where computed is better:

javascript
<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?

javascript
const sum = computed(() => a.value + b.value)

In the Options API:

javascript
computed: { sum() { return this.a + this.b } }

Two-way computed properties (getter + setter)

A computed property can have both a get and a set:

javascript
<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:

javascript
<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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.