Extracting Reactive Logic
Part of the Fundamentals section of Coddy's Vue journey. Lesson 46 of 55.
A composable is a function that uses Vue reactivity to package reusable stateful logic. This function returns a ref and an action; a component can call it during setup.
// useScore.js
import { ref } from 'vue';
export function useScore(initial) {
const score = ref(initial);
function add() { score.value += 5; }
return { score, add };
}
// In a component: const { score, add } = useScore(10);The use naming convention signals a composable, but the function is ordinary JavaScript. Keep the state and its update rules together, and return a small interface the component needs. The component remains responsible for rendering controls and text.
Challenge
MediumExtract a useCredits(initial) composable into useCredits.js. Create its credit ref inside the function and return { credits, earn }. earn() adds two. In App.vue, call it with 3, display credits in #result, and wire #earn to its action.
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