Menu
CoddyTech

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 icon

Challenge

Medium

Extract 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>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals