Summary

In this lesson, you learned that:

  • A composable is a function whose name starts with use. It uses Vue's ref, computed, watch or lifecycle hooks, and returns what a component needs: refs, computed values, functions.
  • It's in a .js file of its own, exported by its name: export function useCounter(start) { … }. A component imports it in braces, import { useCounter } from "./useCounter.js";, and calls it at the top of <script setup>.
  • It returns several things in an object, which the component takes apart, const { count, increase } = useCounter(0);, or a single ref, const name = useLocalStorage("name", "");.
  • Parameters make it fit more uses: useLocalStorage(key, initial) saves anything under any key, and useFetch(url) loads any file.
  • Each call creates new refs, so each component has its own state. Lifecycle hooks in a composable belong to the component that called it: useFetch() loads when that component is mounted.
  • State that several components share is a ref outside any function, in a module, such as export const order = ref([]); in order.js, with the functions that change it next to it. A module runs only once, so every file that imports it gets the same ref. Bigger apps use Pinia for that.

In the next lesson, Final Project, you'll put the whole course together in an app of your own, a habit tracker, and see how to make Vue apps on your own computer.

But first, practice with a composable that counts how long a component has been on the page. App.vue and Timer.vue will both use it, and each will count for itself.

Instructions

  1. In useSeconds.js, write useSeconds(): it creates a ref seconds with 0, increases it by 1 every second from when the component is mounted, stops the interval when the component is unmounted, and returns seconds. Use it in Timer.vue: const seconds = useSeconds();.

  2. Use it in App.vue too, and show its seconds in place of the 0 in the first paragraph. Then click Served: the timer of the order goes away and stops, and the time you've been here goes on, because each component has its own seconds and its own interval.