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 |
computed(() => ...)takes a function that returns a value. This function is called a getter. The result ofcomputed()is a ref you can only read.- Inside the getter, reactive data is still read through
.value. The computed's result is read astotal.valuein the script, and just{{ total }}in the template. - Vue notes which reactive data the getter reads, here
priceandcount. The data it reads are its dependencies (the ingredients of the calculation). As soon as one changes,totalis calculated again. - The exercises use the same pattern.
computed(() => price.value * count.value)withprice50 andcount3 gives150.computed(() => firstName.value + " " + lastName.value)givesBudi Santoso. The space in the middle is joined in too, so the two names don't run together. - In a real project, import both:
import { ref, computed } from "vue". In the exercise editor they're already available.
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
})
- An arrow function with curly braces returns nothing without a
return. The computed isundefined, and{{ total }}shows nothing, with no error.
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.
- Use a computed for a value calculated from reactive data: a total, a full name, a filtered list.
- Use a method when the result really must be new on every render, such as the current time.
const time = computed(() => Date.now())shown in a template never changes.Date.now()isn't reactive data, so this computed has no dependency that could start a new calculation.
📌 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"
getruns whenfullNameis read, just like a normal getter.setis called whenfullName.valueis given a value, here"Siti Aminah".setdoesn't store that value itself.setsplits it and changes the source data,firstNameandlastName. Thengetcalculates again from that data.
⚠️ Why is the total blank, NaN, or stuck?
- A getter with curly braces but no
returnmakes the computedundefined, and nothing shows. Remove the braces or add areturn. const total = price.value * count.valuein a plain variable is calculated once, when the script runs. Ifcountchanges,totaldoesn't. In the exercises, the checker makes sure your code callscomputed(...).price * countwithout.valueinside the getter multiplies two ref boxes, not their numbers. The result isNaN(not a number).- A getter should only calculate and return a value. If a getter raises
countor calls a server, the results become unpredictable. Put changes like that in a method.
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.