Derived Composable Values
Part of the Fundamentals section of Coddy's Vue journey. Lesson 48 of 55.
A composable can return computed refs alongside source refs. The derived value remains connected after the caller destructures the returned object.
function useArea() {
const width = ref(3);
const height = ref(5);
const area = computed(() => width.value * height.value);
return { width, height, area };
}Keep the calculation inside the composable so every consumer follows one rule. Return the computed ref itself, not its current value. The component can edit source refs and display the derived result without maintaining a second manual total.
Challenge
MediumCreate useBasket() with quantity ref 2, price ref 7, a computed total, and an add() action. Return the refs and action. Display total in #result and quantity in #quantity; #add increases quantity by one.
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
7Reusable Components
Importing ComponentsIndependent InstancesPassing PropsProp Types and DefaultsRecap: Component Cards10Reusable Composables
Extracting Reactive LogicReturning Live RefsDerived Composable ValuesIndependent Composable CallsRecap: Donation Logic2Reactive 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