Summary
In this lesson, you learned that:
- A composable is a function whose name starts with
use. It uses Vue'sref,computed,watchor lifecycle hooks, and returns what a component needs: refs, computed values, functions. - It's in a
.jsfile 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, anduseFetch(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([]);inorder.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, writeuseSeconds(): it creates a refsecondswith 0, increases it by 1 every second from when the component is mounted, stops the interval when the component is unmounted, and returnsseconds. Use it inTimer.vue:const seconds = useSeconds();. - 2
Use it in
App.vuetoo, and show itssecondsin place of the 0 in the first paragraph. Then clickServed: the timer of the order goes away and stops, and the time you've been here goes on, because each component has its ownsecondsand its own interval.