Computed Properties — Vue

const total = computed(() => price.value * count.value) makes a derived value, which is a value calculated from other reactive data. total is calculated again…

The Fried Rice order now has price and count, and both are refs. The total is the price times the count, and you could write it directly in the template: {{ price * count }}. There are two problems. That total appears in the cart, on the receipt and on the pay button, so the same formula is written three times. The formula is also calculated again every time the page renders, which means every time Vue builds the view from the template again.

A computed solves both problems. A computed is a value calculated from other reactive data. You write its formula once in the script, and Vue remembers its result until one of its ingredients changes. Picture the whiteboard at the till of Mrs. Sri's stall. When an order comes in, Mrs. Sri calculates the total once and writes it on the board. If the customer asks "what's the total?" five times, she just reads the board. She only calculates again when the number of portions or the price changes. The whiteboard is a computed. A cashier who calculates the total again every time anyone asks is a method (a plain function called from the template).

A derived value with computed()

In this code, total is a derived value, which means a value calculated from other data:

const price = ref(15)
const count = ref(2)

const total = computed(() => price.value * count.value)

---template---
<p>Fried Rice × {{ count }}</p>
<p>Total: ${{ total }}</p>
<button @click="count++">+1 portion</button>

This table shows count and total each time the button is clicked:

What happens count total
The page shows 2 30
Click +1 portion 3 45
Click +1 portion 4 60

The getter has to return a value

Here are three ways to write the same getter. The first is wrong, the other two are right:

// wrong: curly braces with no return, total becomes undefined
const total = computed(() => { price.value * count.value })

// right: no curly braces, the result is returned straight away
const total = computed(() => price.value * count.value)

// also right: curly braces with return
const total = computed(() => {
  return price.value * count.value
})

A computed remembers its result

This component calculates the same total in two ways: the computed total and the method calculateTotal(). Both write to the console each time they run:

const price = ref(15)
const count = ref(2)
const note = ref("")

const total = computed(() => {
  console.log("computed total calculated")
  return price.value * count.value
})

function calculateTotal() {
  console.log("method calculateTotal called")
  return price.value * count.value
}

---template---
<p>Total: ${{ total }} · Pay: ${{ total }}</p>
<p>Total: ${{ calculateTotal() }} · Pay: ${{ calculateTotal() }}</p>
<p>Note: {{ note }}</p>
<button @click="note += 'spicy '">Add note</button>
<button @click="count++">+1 portion</button>

Try counting before you look at the table. The customer presses "Add note" three times. note changes, so the page re-renders three times, but price and count don't change. Since the page appeared, how many times has the total getter run?

What happens total (computed) runs calculateTotal() (method) is called
First render 1 2
Add note, re-render 0, it uses the remembered result 2
Add note, re-render 0 2
Add note, re-render 0 2
+1 portion, count changes 1 2

The answer is once. From the moment the page appears to the third note click, the page renders four times and total is used in two places, but its getter runs only one time. This remembering is called caching. Caching is the main advantage of a computed over a method. A method is called again on every render, once for each place it's used.

📌 A computed you can write to

A normal computed can only be read. total.value = 0 changes nothing. In development mode, the console writes [Vue warn] Write operation failed: computed value is readonly. If a computed really needs to be given a value, give it a get and a set:

const firstName = ref("Budi")
const lastName = ref("Santoso")

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

fullName.value = "Siti Aminah"
// firstName.value = "Siti", lastName.value = "Aminah"

⚠️ Why is the total blank, NaN, or stuck?

TL;DR: const total = computed(() => price.value * count.value) makes a derived value, which is a value calculated from other reactive data. total is calculated again by itself when price or count changes. In the script you read total.value; in the template, just {{ total }}. Its main advantage is caching: Vue remembers the result. The getter (the function inside computed()) doesn't run again until a dependency (data it reads) changes. A method (a plain function), on the other hand, is called again on every render, which is every time Vue builds the view again. A getter with curly braces needs a return. A normal computed can only be read. To give it a value, give the computed a get and a set.

⚡ A derived value with computed

Write:

const price = ref(15)
const count = ref(2)

const total = computed(() => price.value * count.value)

---template---
<p>Fried Rice × {{ count }}</p>
<p>Total: ${{ total }}</p>
<button @click="count++">+1 portion</button>

Meaning: A computed calculates a value from other reactive data. As soon as price or count changes, total is calculated again by itself. So when +1 portion is clicked, the total becomes 45. In the script read it as total.value; in the template, just {{ total }}.

⚡ The getter has to return a value

Guess first: the function inside computed() is called a getter. This getter uses curly braces: computed(() => { price.value * count.value }). In the template, what does the total show?

Nothing, and there's no error either. An arrow function with curly braces and no return returns nothing, so the computed is undefined.

Meaning: A getter has to return a value. Remove the curly braces, or add a return.

⚡ A computed remembers its result

Guess first: say the total from the first step is shown in two places. The customer presses the "Add note" button three times. That button only changes the data note, so the page re-renders (is built again from the template) three times, but price and count don't change. Since the page appeared, how many times has the total getter run?

Only once, when the page first appeared. Vue uses the remembered result until one of its dependencies (the data the getter reads: price or count) changes.

Meaning: This remembering is called caching, the main advantage of a computed. A method (a plain function called from the template) is called again on every render, once for each place it's used.

What you will learn