🎓 A1Learner
🔍
0 of 50 lessons completed

Computed Properties

A computed property is a value Vue works out from other values. Vue works it out again when one of those values changes.

Create a computed value

The count starts at 3.

import { ref, computed } from 'vue'
const count = ref(3)
const doubled = computed(() => count.value * 2)

A computed string

The name is Ana.

import { ref, computed } from 'vue'
const name = ref('Ana')
const greeting = computed(() => 'Hi, ' + name.value)

It follows its source

The count changes to 5.

import { ref, computed } from 'vue'
const count = ref(3)
const doubled = computed(() => count.value * 2)
count.value = 5

Example

<script setup>
import { ref, computed } from 'vue'
const price = ref(4)
const count = ref(3)
const total = computed(() => price.value * count.value)
</script>
<template>
  <div>
    <p>Price: {{ price }}</p>
    <p>Count: {{ count }}</p>
    <p>Total: {{ total }}</p>
  </div>
</template>

Key points

  • Call computed with a function that returns a value.
  • The function reads one or more reactive values.
  • computed returns a holder, like the one ref makes.
  • Read the result through .value in script code.
  • Write the plain name in the template, with no .value.

In this example, the script makes a price of 4 and a count of 3. It makes a total with computed, by multiplying price by count. The template shows the price, the count, and the total. The page first shows Total: 12. If the price changes to 5, the total becomes 15.

Note

Use computed for a value that comes from other values.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

When does a computed value run again?