Computed Values
Part of the Fundamentals section of Coddy's Vue journey. Lesson 11 of 55.
A computed ref derives a value from reactive inputs. With price equal to 6 and quantity equal to 2, this getter returns 12. Increasing quantity makes the next value 18.
import { ref, computed } from 'vue';
const price = ref(6);
const quantity = ref(2);
const cost = computed(() => price.value * quantity.value);The getter reads its dependencies and returns a result. Vue caches that result until a dependency changes. Keep the getter free of side effects: update source refs in handlers and let the derived value follow them. Templates unwrap computed refs too.
Challenge
EasyA donation table has 3 boxes with 4 books each. Use a computed ref to display the total books in #result. Button #box adds a box.
Try it yourself
<!doctype html><html><head><meta charset="UTF-8"><title>Vue practice</title></head><body><div id="app"></div><script type="module" src="./main.js"></script></body></html>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
2Reactive State
Reactive RefsUpdating Refs in ScriptEvent Handler ArgumentsReactive ObjectsRecap: Reactive State5Conditions and Lists
Conditional BranchesShow without UnmountingRendering ListsStable List IdentityRecap: Conditions8Component Communication
Emitting EventsEvent PayloadsLifting Shared StateDefault and Named SlotsRecap: Shared Panel11Project: Community Board
Board StructureAdding Community Tasks