Vue Computed

Create cached values derived from reactive component state.

Overview

Computed properties describe values calculated from other reactive data. Vue tracks their dependencies, caches each result, and recalculates only when a dependency changes. They keep templates clean and are ideal for full names, totals, filtered collections, averages, and other derived display values.

Key concepts

  • Computed values depend on reactive state
  • Results are cached between dependency changes
  • Templates access them like ordinary properties
  • Computed getters should remain free of side effects

What are Computed Properties?

A computed property is a derived value that Vue calculates from component state. Think of it as a reactive formula: firstName and lastName can produce fullName, and changing either source automatically produces a new result.

Output
First name: John
Last name:  Doe
Computed full name: John Doe

Why do we need Computed Properties?

An online store may calculate totals from price and quantity. Keeping that formula in a computed property avoids repeating calculations in the template or manually synchronizing a separate total whenever either source changes.

  • Cleaner templates
  • Reusable derived values
  • Automatic dependency tracking
  • Cached calculations
  • A single source of truth

Creating a Computed Property

With the Options API, define derived values in the computed option. Use the computed name as a property in the template rather than calling it as a function.

Vue SFC
<script>
export default {
  data() {
    return {
      firstName: "John",
      lastName: "Doe"
    };
  },

  computed: {
    fullName() {
      return this.firstName + " " + this.lastName;
    }
  }
};
</script>

<template>
  <h2>{{ fullName }}</h2>
</template>

Composition API computed

In script setup, import computed and pass it a getter function. Refs use .value in JavaScript but are automatically unwrapped in templates.

Vue SFC
<script setup>
import { computed, ref } from "vue";

const firstName = ref("John");
const lastName = ref("Doe");

const fullName = computed(
  () => firstName.value + " " + lastName.value
);
</script>

<template>
  <h2>{{ fullName }}</h2>
</template>

How Computed Properties work

While evaluating fullName, Vue records that it reads firstName and lastName. Re-renders caused by unrelated state can reuse the cached result. Changing either recorded dependency invalidates the cache and causes a recalculation the next time fullName is read.

Computed vs Methods

A method can return the same output, but it runs whenever the template calls it during rendering. A computed getter reuses its cached result until a reactive dependency changes.

FeatureComputed propertyMethod
Template usage{{ fullName }}{{ fullName() }}
CachingYesNo
Re-evaluationWhen a dependency changesWhenever called during render
Best useDerived reactive stateActions or always-fresh calculations

Shopping Cart example

Vue SFC
<script setup>
import { computed, ref } from "vue";

const price = ref(500);
const quantity = ref(3);
const totalPrice = computed(() => price.value * quantity.value);
</script>

<template>
  <input v-model.number="quantity" type="number" min="1">
  <p>Total: {{ totalPrice }}</p>
</template>

The total begins at ₹1500. Changing quantity to 5 updates it to ₹2500 automatically.

Computed collections

Computed values are also useful for filtering and sorting without mutating the original collection.

JavaScript
const matchingProducts = computed(() =>
  products.value.filter((product) =>
    product.name.toLowerCase().includes(query.value.toLowerCase())
  )
);

Writable Computed Properties

Computed properties are read-only by default. When a derived value needs controlled write behavior, provide get and set functions. Use this sparingly because explicit state updates are often clearer.

JavaScript
const fullName = computed({
  get: () => firstName.value + " " + lastName.value,
  set: (value) => {
    [firstName.value, lastName.value] = value.split(" ");
  }
});

Real-life example

A student record can derive total marks, average marks, and a grade from subject scores. Editing any score automatically updates all dependent computed values without storing duplicate totals.

Computed vs Watch

NeedUse
Return a value derived from stateComputed
Perform a side effect after state changesWatch
Cache a calculationComputed
Call an API or write storageWatch or an explicit action

Common beginner mistakes

  • Calling a computed property like a method
  • Changing other state inside a computed getter
  • Trying to assign to a read-only computed value
  • Using a method for an expensive repeated derivation
  • Expecting caching when dependencies are non-reactive
  • Sorting the source array in place inside a computed getter

Best practices

  • Use computed for values derived from state
  • Give computed values descriptive names
  • Keep getters deterministic and side-effect free
  • Return new arrays when sorting or transforming
  • Use methods for actions
  • Use watchers for side effects
  • Break very complex calculations into smaller functions

Key takeaways

  • Computed properties derive values from reactive data
  • Vue tracks dependencies automatically
  • Results remain cached until dependencies change
  • Templates access computed values as properties
  • Computed values keep calculations out of markup
  • Methods are uncached
  • Watchers handle side effects
  • Pure computed getters improve clarity and maintainability
Let's learn with DevBrainBox AI