Returning Live Refs
Part of the Fundamentals section of Coddy's Vue journey. Lesson 47 of 55.
Return a ref itself when callers need a live value. Returning its .value instead gives a snapshot at the moment the function returns.
function useLabel() {
const label = ref('Ready');
function reset() { label.value = 'Ready'; }
return { label, reset };
}
const { label, reset } = useLabel();A plain object containing refs can be destructured without losing those refs. The component can bind a returned ref with v-model, and actions in the composable still update the same object. This differs from destructuring primitive fields out of a reactive object.
Challenge
MediumComplete useName.js so it returns the name ref itself, initially Neighbor, plus a reset action. The supplied app destructures the returned object, binds #name, and displays the current value inside brackets in #result. Button #reset must update both the input and display.
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