By the end of the testing module, Colmena Bookings was protected by a safety net of unit and end-to-end tests, and along the way it became clear that some logic is repeated or trapped inside the views: the catalogue's filters synchronised with the URL live entirely in RoomsView; we have already written the "fetch data with its loading state, its error and its cancellation" pattern several times; and the rules for a room's availability (which hours are free on a given day) do not exist anywhere yet, even though the room's spec sheet and the booking form both need them. The Composition API has an answer for all of this: composables, functions that encapsulate logic with reactive state and that any component can reuse. You have already used them without writing them (useRoute, useI18n, Pinia stores, useFormat). In this lesson you will learn to design them well: their conventions, how they accept reactive arguments, how they manage their effects and their clean-up, where they can be called and why. Then you will create Colmena's three composables (useRequest, useRoomFilters and useAvailability), refactor the views to use them, test them with withHost and get to know VueUse, the go-to composables library.
Contents
- What a composable is and what problem it solves
- The precedent: Vue 2 mixins
- Conventions of a good composable
- Flexible arguments: values, refs and getters with
toValue - Per-instance state and shared state
- Effects and clean-up:
onScopeDisposeandeffectScope - Asynchronous composables
- Where a composable can be called (and why
getCurrentInstanceis not the way out) - Colmena:
useRequest - Colmena:
useRoomFilters - Colmena:
useAvailability - Testing the composables with
withHost - VueUse: the go-to library
- Try it
- What a composable is and what problem it solves
A composable is a function that uses the Composition API (ref, computed, watch, lifecycle hooks, inject...) to encapsulate and reuse stateful logic. It differs from two close relatives:
| Piece | What it reuses | Example in Colmena |
|---|---|---|
| Utility function | Stateless logic: a value goes in, another comes out | toMinutes, toISODate in src/utils/dates.js |
| Composable | Logic with reactive state that lives as long as the component using it | useFormat, and the ones we will create in this lesson |
| Component | Logic and markup | RoomCard, RoomFilters |
In 01-05 we sketched useOccupancy and saw the central idea: with the Composition API, code is organised by feature, not by type of option. A composable is the next step: moving that feature out of the component into a named function, in its own file.
flowchart LR
subgraph Before["Before: logic inside each view"]
VS["RoomsView<br/>filters + URL + sorting"]
VD["RoomDetailView<br/>(no availability)"]
FR["BookingForm<br/>(no slot checking)"]
end
subgraph After["After: reusable composables"]
UF["useRoomFilters"]
UD["useAvailability"]
UP["useRequest"]
end
UF --> VS2["RoomsView"]
UD --> VD2["RoomDetailView"]
UD --> FR2["BookingForm"]
UP --> VF["DashboardInvoicesView"]
What do we gain by extracting the logic?
- Reuse without copying and pasting: a room's availability is calculated in the same way in the spec sheet and in the form.
- More readable views:
RoomsView's<script setup>goes from a hundred or so lines about filters to a single call. - Smaller tests: the composable is tested once, without mounting the whole view, and the views are tested relying on it.
- The precedent: Vue 2 mixins
Before the Composition API, the way to reuse logic between components was mixins: objects with options (data, computed, methods, hooks) that Vue merged with the component's own. You will find plenty of them in older projects:
// roomFiltersMixin.js (Vue 2, Options API) — for comparison only, do not use it
export default {
data() {
return { search: '', sort: 'none' }
},
computed: {
visibleRooms() {
// Where does this.rooms come from? From the component that uses the mixin... hopefully
return this.rooms.filter((room) => room.name.includes(this.search))
}
},
methods: {
clear() {
this.search = ''
}
}
}// In the component
export default {
mixins: [roomFiltersMixin, requestMixin],
// What comes from each mixin? You only find out by opening them
}Mixins work, but they have underlying problems that the Composition API solves:
| Problem with mixins | What it consists of | How a composable solves it |
|---|---|---|
| Unclear origin | visibleRooms appears in the template and there is no way of knowing which mixin it comes from |
It is destructured explicitly: const { visibleRooms } = useRoomFilters(...) |
| Name collisions | If two mixins define loading, one silently overwrites the other |
You rename when destructuring: const { loading: loadingInvoices } = useRequest(...) |
| Implicit dependencies | The mixin reads this.rooms and takes it for granted that the component has it |
The composable receives what it needs as an argument |
| No parameters or multiple instances | You cannot use the same mixin twice with different data | You call the function twice with different arguments |
| Difficult typing | this mixes options from different sources |
Ordinary functions: TypeScript infers them (09-02) |
Vue 3 still supports mixins for compatibility, but the official recommendation is to use composables in new code.
- Conventions of a good composable
Conventions are not whims: they mean that anyone reading useSomething() knows what to expect.
| Convention | Why |
|---|---|
A name with the use prefix in camelCase: useRoomFilters |
It signals that it has state and must be called in setup (like React hooks, where the habit comes from) |
One file per composable in src/composables/ (useRoomFilters.js) |
It can be found straight away; its tests go in src/composables/__tests__/ |
It returns an ordinary object of refs (and functions), not a reactive |
It can be destructured without losing reactivity |
It accepts values, refs or getters and normalises them with toValue |
The caller chooses whether the argument is fixed or reactive |
| It cleans up its effects (timers, listeners, requests) | When the component unmounts, no orphaned effects must remain |
It does not modify the DOM directly unless that is its purpose, and then it does so in onMounted |
The DOM does not exist during setup (and in SSR it never exists, 09-06) |
The convention of returning refs deserves an example. Compare:
// Returns a reactive: destructuring it breaks reactivity
function useCounterBad() {
return reactive({ value: 0 })
}
const { value } = useCounterBad() // value is the number 0, it is no longer connected
// Returns an object of refs: destructuring it is safe
function useCounter() {
const value = ref(0)
const increment = () => value.value++
return { value, increment }
}
const { value, increment } = useCounter() // value is still a refIf someone prefers to treat the result as an object (counter.value instead of value.value), they can wrap it themselves: const counter = reactive(useCounter()). It is the same idea as storeToRefs in Pinia, but the other way round.
- Flexible arguments: values, refs and getters with
toValue
toValueA composable that receives data must allow for that data changing. The spec sheet's room changes when you navigate from /rooms/polen to /rooms/nectar (the view is reused, as we saw in 04-03), and the form's date changes every time the user picks another one. There are three ways of passing a piece of data:
| Form | Example | Reactive? |
|---|---|---|
| Plain value | useAvailability('polen', '2026-11-03') |
No: always the same room and date |
| Ref | useAvailability(roomId, selectedDate) |
Yes: it follows roomId.value |
| Getter (function) | useAvailability(() => id, () => form.date) |
Yes: it follows whatever the function reads |
toValue (Vue 3.3+) normalises all three: if it receives a ref, it returns .value; if it receives a function, it calls it; if it receives anything else, it returns it as it is.
import { computed, toValue } from 'vue'
export function useRoomName(roomId, rooms) {
// toValue inside the computed: it is read on every evaluation and the dependency is recorded
return computed(() => toValue(rooms).find((room) => room.id === toValue(roomId))?.name ?? '')
}The key lies in where toValue is called: inside a computed, a watch or a watchEffect, so that Vue records the dependency on every read. If you called it once at the start of the function (const id = toValue(roomId)), you would copy the value at that instant and the composable would stop reacting.
In TypeScript, the type of these arguments is
MaybeRefOrGetter<T>("aT, a ref ofTor a function that returnsT"). We will use it when typing the composables in 09-02. The olderunrefonly understands values and refs, not getters.
A case that bites: destructured props
Since Vue 3.5, const { id } = defineProps(...) keeps its reactivity inside the component: the compiler translates every use of id into __props.id. But if you pass id as it is to a function, the compiler cannot work any magic: the function receives the string of that moment.
const { id } = defineProps({ id: { type: String, required: true } })
useAvailability(id, date) // WRONG: it receives 'polen' and keeps 'polen' forever
useAvailability(() => id, date) // RIGHT: the getter reads __props.id every timeVue warns you with a compilation error if you pass a destructured prop to watch or toRef, but it cannot know about your own functions. A rule of thumb: a destructured prop is always passed to a composable wrapped in a getter.
- Per-instance state and shared state
By default, each call to a composable creates its own state, because the refs are created inside the function:
If two components call useCounter(), each one has its own counter. That is what we want almost every time: two room spec sheets open in catalogue tabs must not share the date being checked.
But if the ref is declared outside the function, at module level, everyone who calls the composable will share the same state:
// Module state: shared by every component that uses it
const notifications = ref([])
export function useNotifications() {
function notify(text) {
notifications.value.push({ id: crypto.randomUUID(), text })
}
return { notifications, notify }
}This is exactly the technique we used in 03-07 and in the provisional src/session.js of module 4, and which we replaced with Pinia in module 5. The reasons still hold:
| Module state in a composable | Pinia store | |
|---|---|---|
| Visible in Vue DevTools | No | Yes, with a timeline of changes |
| Isolated per application (several apps, tests, SSR) | No: a single state for the whole process | Yes: one Pinia per application |
Persistence, $reset, $subscribe, plugins |
By hand | Included or via plugins |
| Suitable for | Very local, ephemeral interface state (a notification counter, a debug mode) | Shared domain data: rooms, bookings, session |
The rule for Colmena: if the state represents domain data or distant screens need it, it goes into a store. A composable can use a store internally (useAvailability will) without becoming one. Isolation is especially important in SSR: module state on the server would be shared between requests from different users, as you will see in 09-06.
- Effects and clean-up:
onScopeDispose and effectScope
onScopeDispose and effectScope6.1 A composable's effects
A composable can create effects: watch, watchEffect, computed, timers, event listeners, requests in progress. When it is called inside setup, watch and computed are automatically bound to the component and stopped when it unmounts. But anything that is not reactive (a setInterval, an addEventListener, a request) has to be cleaned up by hand.
You already know onUnmounted (01-04) and onWatcherCleanup (02-05). For composables there is a more general option, onScopeDispose:
import { ref, onScopeDispose } from 'vue'
export function useCurrentTime(intervalMs = 1000) {
const now = ref(new Date())
const timer = setInterval(() => (now.value = new Date()), intervalMs)
// Runs when the "scope" that called the composable is destroyed
onScopeDispose(() => clearInterval(timer))
return { now }
}onUnmounted |
onScopeDispose |
|
|---|---|---|
| Works inside a component | Yes | Yes (the component is a scope) |
Works in an effectScope outside components |
No | Yes |
| Works inside a Pinia store | No | Yes (each store is a scope) |
That is why, in composables, we prefer onScopeDispose: the composable works in the same way whether it is called from a component, from a store or from a scope created by hand. If you call it outside any scope, Vue warns you in development: "onScopeDispose() is called when there is no active effect scope".
6.2 effectScope: grouping effects outside components
An effect scope is a container that collects all the effects created while a function runs, so that they can all be stopped at once. Every component has its own, and Pinia creates one per store. You can create your own with effectScope():
import { effectScope } from 'vue'
import { useCurrentTime } from '@/composables/useCurrentTime.js'
const scope = effectScope()
// Everything created in here (refs, watch, computed, onScopeDispose) belongs to the scope
const { now } = scope.run(() => useCurrentTime())
// Later: stops the effects and runs the onScopeDispose callbacks (the interval is cleared)
scope.stop()When is it needed? Rarely in an application, but it is the piece underneath two common patterns:
- Shared composables: a single timer for all the components that show the time, created with the first one that asks for it and destroyed when the last one goes away. VueUse offers it ready-made as
createSharedComposable(section 13); exercise 3 asks you to write your own version. - Libraries and stores: Pinia runs each store's
setupinside aneffectScope. That is why a setup store can usecomputedandwatchwithout being a component, and why its effects stop when$dispose()is called.
- Asynchronous composables
Many composables work with asynchronous data. The temptation is to write them as async functions:
// Tempting, but problematic
export async function useInvoices(month) {
const invoices = ref(await api.invoices.fetchInvoices({ month }))
onScopeDispose(() => { /* ... */ }) // is there still an active scope after the await?
return { invoices }
}There are two problems. First, whoever uses it has to do await useInvoices(...) in setup, which turns the component into an async one: Vue will not render it until the promise resolves, and to show anything in the meantime you need <Suspense> (09-05). Second, after the first await, Vue no longer knows which component is being set up, so hooks, inject and onScopeDispose called afterwards may not be bound to anything.
The recommended pattern is the opposite: the composable returns its refs immediately, empty, and fills them when the data arrives. The component renders straight away, with its loading state:
// Recommended pattern: synchronous on the outside, asynchronous on the inside
export function useInvoices(month) {
const invoices = ref(null)
const loading = ref(true)
api.invoices.fetchInvoices({ month }).then((list) => {
invoices.value = list
loading.value = false
})
return { invoices, loading }
}This is the shape of useFetch in Nuxt, of useQuery in TanStack Query and of our stores' actions, which never reject and leave the error in the state. useRequest (section 9) generalises this pattern.
- Where a composable can be called (and why
getCurrentInstance is not the way out)
getCurrentInstance is not the way out)8.1 The synchronous context of setup
Composables that use lifecycle hooks or inject need to know which component they belong to. Vue solves this with an internal variable, the "current instance", which it sets just before running setup and clears just after. onMounted(fn) does not receive the component as an argument: it takes it from that variable.
sequenceDiagram
participant V as Vue
participant S as setup()
participant C as useSomething()
V->>V: currentInstance = component
V->>S: runs setup
S->>C: synchronous call
C->>V: onMounted(fn) → bound to currentInstance
S-->>V: setup finishes
V->>V: currentInstance = null
Note over V,C: An onMounted called now (in a click, after an await, in a setTimeout) has no component
That gives us the rules:
| Where | Can a composable be called? |
|---|---|
At the top level of <script setup> or of setup() |
Yes |
Inside another composable, which is in turn called in setup |
Yes |
In an event handler (function onClick() { useSomething() }) |
No |
Inside a setTimeout, a .then or an async function of your own, after an await |
No |
At the top level of <script setup> after an await |
Yes: the <script setup> compiler restores the instance after each top-level await |
| In a Pinia store (setup store), a router guard or a plugin | It depends: those that only use reactivity, inject and onScopeDispose work; those that use component hooks such as onMounted do not |
Some composables, such as useFormat (07-02), check the context with hasInjectionContext() and throw a clear error if they are used in the wrong place. It is good practice for composables that depend on inject.
8.2 getCurrentInstance: discouraged
getCurrentInstance() returns that internal instance, and on the internet you will find code that uses it to access proxy.$router, proxy.$t or appContext.config.globalProperties. Do not do it in application code:
- It is an internal API: its shape can change between minor versions without warning.
- It ties the composable to "being inside a component", exactly the opposite of what we are after.
- There is always a public alternative:
| Instead of | Use |
|---|---|
getCurrentInstance().proxy.$router |
useRouter() |
getCurrentInstance().proxy.$t |
useI18n() |
getCurrentInstance().appContext.config.globalProperties.$format |
useFormat(), which injects the service (07-02) |
getCurrentInstance().attrs / .slots |
useAttrs() / useSlots() |
| Checking whether there is a component | hasInjectionContext() or getCurrentScope() |
Libraries sometimes use it internally, knowing exactly what they are doing. In an application, if you find yourself writing it, look for the public API you need.
- Colmena:
useRequest
useRequest9.1 The repeated pattern
You have written the same logic three times: in App.vue in 02-05 (the catalogue by floor), in RoomDetailView in 04-03 (the room from the route param) and, in another form, in the stores' actions. Always the same pieces: data, loading, error, an AbortController to cancel the previous request when the parameter changes, and a function for retrying.
The shared data (catalogue, bookings, session) is already in the stores, and that is where it should stay. But there is data that only one screen needs and that it makes no sense to keep in a store: the invoices a manager consults in "Invoices" are the typical case. Today DashboardInvoicesView has three invoices written into the component itself, since 04-04. We will move them to the simulated API and request them with a generic composable.
9.2 The composable
Create src/composables/useRequest.js:
// src/composables/useRequest.js
// State of an asynchronous request (data, loading, error) that is repeated when its
// source changes, cancels the previous request and is cleaned up when the component unmounts.
import { ref, shallowRef, watch, toValue, onScopeDispose } from 'vue'
export function useRequest(loader, source) {
const data = shallowRef(null)
const loading = ref(false)
const error = shallowRef(null)
let controller = null // the request in progress; private to each call to the composable
async function reload() {
controller?.abort() // the previous one is no longer of interest
const own = new AbortController()
controller = own
loading.value = true
error.value = null
try {
const result = await loader(toValue(source), { signal: own.signal })
if (controller === own) data.value = result
} catch (e) {
if (controller === own) error.value = e // the whole object, for translateError
} finally {
if (controller === own) {
loading.value = false
controller = null
}
}
}
// First load, and a new one every time the source changes
watch(() => toValue(source), () => reload(), { immediate: true })
// When the component unmounts (or the scope stops), anything pending is cancelled
onScopeDispose(() => controller?.abort())
return { data, loading, error, reload }
}Let's analyse each decision:
- The signature
useRequest(loader, source):loaderis a function(param, { signal }) => Promise, the same shape that every function insrc/api/has;sourceis the parameter, which can be a value, a ref or a getter. shallowReffordataanderror: the data that arrives from the API is replaced as a whole, never modified internally, so there is no need for Vue to make every object in the array reactive. It is cheaper, and we will come back to it in 09-07.controller === own: each call toreloadcreates its own controller and checks, when it finishes, that it is still the current request. That way, if an old response arrives late (because the loader did not respect the signal), it does not overwrite the new data. It is the race condition you studied in 02-05, solved once and for all.- The whole error, not its message: following the rule from 07-03, the view will translate it with
translateErrorwhen displaying it. Cancellation errors (AbortError) are never displayed: if the request is cancelled because the source changed, there is already another current one and the check discards them; if it is cancelled on unmounting, there is no longer a screen on which to show them. watchwithimmediateon() => toValue(source): it does the first load and repeats it when the source changes. If the source is a fixed value, thewatchruns only once.onScopeDisposecancels the pending request if the user leaves the screen before the response arrives.reloadis public: it is used for the "Retry" button.
9.3 The invoices API
Create src/api/invoices.js with the data that is in the view today, plus a few from September so that the month can be changed:
// src/api/invoices.js
// Simulated invoicing API (fictitious data, read-only)
import { wait, randomDelay, failSometimes } from './simulation.js'
const INVOICES = [
{ number: 'INV-2026-0127', date: '2026-09-01', client: 'Laura Gómez', description: 'Flexible plan · 8 room hours', amount: 200, paid: true },
{ number: 'INV-2026-0128', date: '2026-09-01', client: 'Estudio Alveolo S.L.', description: 'Business plan · September', amount: 1450, paid: true },
{ number: 'INV-2026-0141', date: '2026-10-01', client: 'Laura Gómez', description: 'Flexible plan · 12 room hours', amount: 300, paid: true },
{ number: 'INV-2026-0142', date: '2026-10-01', client: 'Estudio Alveolo S.L.', description: 'Business plan · October', amount: 1450, paid: false },
{ number: 'INV-2026-0143', date: '2026-10-02', client: 'Jaime Ortega', description: 'Fixed plan · October', amount: 220, paid: true }
]
// month: 'YYYY-MM'
export async function fetchInvoices({ month }, { signal } = {}) {
await wait(randomDelay(), signal)
failSometimes()
return structuredClone(INVOICES.filter((invoice) => invoice.date.startsWith(month)))
}And register it in src/api/index.js, so that components use it through api and tests can mock it with vi.mock('@/api'):
// src/api/index.js
import * as rooms from './rooms.js'
import * as bookings from './bookings.js'
import * as session from './session.js'
import * as invoices from './invoices.js'
export const api = { rooms, bookings, session, invoices }Since fetchInvoices uses wait, randomDelay and failSometimes, it automatically respects the stable mode of the E2E tests (VITE_STABLE_SIMULATION, 08-04).
9.4 DashboardInvoicesView with useRequest
Replace the script of src/views/dashboard/DashboardInvoicesView.vue:
<script setup>
import { ref, computed } from 'vue'
import { api } from '@/api'
import { useRequest } from '@/composables/useRequest.js'
import { translateError } from '@/i18n.js'
import BaseButton from '@/components/base/BaseButton.vue'
const month = ref('2026-10') // the fictitious data covers September and October 2026
const { data: invoices, loading, error, reload } = useRequest(
(chosenMonth, options) => api.invoices.fetchInvoices({ month: chosenMonth }, options),
month
)
const outstanding = computed(() =>
(invoices.value ?? []).filter((i) => !i.paid).reduce((total, i) => total + i.amount, 0)
)
</script>And in the template, add the month picker and the states before the table (the rows do not change, except that they now loop over invoices instead of the constant):
<template>
<h2>Invoices</h2>
<label class="month-picker">
Month
<input v-model="month" type="month" min="2026-01" max="2026-12" />
</label>
<p v-if="loading && !invoices">Loading the invoices…</p>
<div v-else-if="error" class="notice" role="alert">
<p>{{ translateError(error) }}</p>
<BaseButton @click="reload">Retry</BaseButton>
</div>
<template v-else-if="invoices">
<p>Outstanding: <strong>{{ $format.price(outstanding) }}</strong></p>
<table class="invoices" :aria-busy="loading">
<!-- thead and rows as before: v-for="invoice in invoices" -->
</table>
</template>
</template>- Renaming when destructuring (
data: invoices) gives each piece of data a meaningful name. If a view needed two requests, each one would have its ownloadingwith no collision, which was precisely the problem with mixins. loading && !invoices: the loading text only appears the first time. When the month changes, the previous table stays visible witharia-busywhile the new one arrives, instead of flickering.- The source's getter is a
refhere (month):useRequestreads it withtoValueand repeats the request when it changes.
- Colmena:
useRoomFilters
useRoomFilters10.1 What is extracted from RoomsView
Since 04-05, the catalogue's filters have lived in the URL (/rooms?floor=2&capacity=4&sort=price-asc&q=nectar), and RoomsView contains all the machinery: urlFilters, applyFilters, filterInUrl and the five writable computeds; then catalog (the rooms on the floor, built on the store since 05-06), catalogEquipment, roomsWithCapacity, visibleRooms with normalize and matchesSearch, and clearFilters. It is logic without markup, with reactive state and dependent on the router: a textbook composable.
What stays in the view: whatever depends on the store and on the presentation (loading, error, currentView, freeRooms, hasResults, the selection and the spec sheet, prepareBooking, copyLink).
flowchart LR
URL["route.query<br/>?floor=2&q=nectar"] --> FU["urlFilters<br/>(validated)"]
FU --> FC["floorFilter, minCapacity,<br/>requiredEquipment, sort, search<br/>(writable computeds)"]
FC -- "set" --> AF["applyFilters()<br/>router.replace"] --> URL
S["rooms (argument)"] --> CA["catalog"]
FC --> CA --> SV["visibleRooms"]
CA --> EQ["catalogEquipment"]
10.2 The composable
Create src/composables/useRoomFilters.js. Almost all of it is the code from 04-05 and 02-08, moved; what is new is the signature and the return:
// src/composables/useRoomFilters.js
// Catalogue filters synchronised with the URL (the URL is the source of truth),
// and the list of rooms filtered and sorted according to them.
import { computed, toValue } from 'vue'
import { useRoute, useRouter } from 'vue-router'
const DEFAULT_VALUES = { floor: null, capacity: 1, equipment: '', sort: 'none', q: '' }
const VALID_SORTS = ['none', 'price-asc', 'price-desc']
function firstValue(value) {
return Array.isArray(value) ? value[0] : value
}
function readInteger(value, min, max, fallback) {
const number = Number(firstValue(value))
return Number.isInteger(number) && number >= min && number <= max ? number : fallback
}
export function normalize(text) {
return text
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.trim()
.toLowerCase()
}
export function useRoomFilters(rooms) {
const route = useRoute()
const router = useRouter()
// --- URL → filters: always valid values of the right type ---
const urlFilters = computed(() => {
const query = route.query
const sort = firstValue(query.sort)
return {
floor: readInteger(query.floor, 1, 3, null),
capacity: readInteger(query.capacity, 1, 100, 1),
equipment: firstValue(query.equipment) ?? '',
sort: VALID_SORTS.includes(sort) ? sort : 'none',
q: firstValue(query.q) ?? ''
}
})
// --- Filters → URL: only those that differ from the default value ---
function applyFilters(changes) {
const next = { ...urlFilters.value, ...changes }
const query = {}
for (const [key, value] of Object.entries(next)) {
if (value !== DEFAULT_VALUES[key]) query[key] = String(value)
}
return router.replace({ query })
}
function filterInUrl(key) {
return computed({
get: () => urlFilters.value[key],
set: (value) => applyFilters({ [key]: value })
})
}
const floorFilter = filterInUrl('floor')
const minCapacity = filterInUrl('capacity')
const requiredEquipment = filterInUrl('equipment')
const sort = filterInUrl('sort')
const search = filterInUrl('q')
// --- Filtering and sorting ---
const catalog = computed(() => {
const all = toValue(rooms)
return floorFilter.value === null ? all : all.filter((room) => room.floor === floorFilter.value)
})
const catalogEquipment = computed(() => {
const everything = catalog.value.flatMap((room) => room.equipment)
return [...new Set(everything)].sort()
})
const visibleRooms = computed(() => {
const text = normalize(search.value)
const filtered = catalog.value.filter(
(room) =>
room.capacity >= minCapacity.value &&
normalize(room.name).includes(text) &&
(requiredEquipment.value === '' || room.equipment.includes(requiredEquipment.value))
)
if (sort.value === 'price-asc') return filtered.toSorted((a, b) => a.hourlyPrice - b.hourlyPrice)
if (sort.value === 'price-desc') return filtered.toSorted((a, b) => b.hourlyPrice - a.hourlyPrice)
return filtered
})
// A single navigation with all the changes (it keeps the floor, as before)
function clearFilters() {
return applyFilters({ capacity: 1, equipment: '', sort: 'none', q: '' })
}
return {
floorFilter, minCapacity, requiredEquipment, sort, search,
catalog, catalogEquipment, visibleRooms,
clearFilters
}
}What changes compared with the view's code:
roomsis an argument, not a direct read from the store. The composable does not know where the rooms come from: from the store inRoomsView, from a fixed array in the tests or, tomorrow, from the public website we will create in 09-06. It reads it withtoValueinsidecatalog.roomsWithCapacityandmatchesSearchhave been merged intovisibleRooms' filter. The normalised search is calculated once per evaluation (text), not once per room.normalizeis exported: it is a pure function that may be useful elsewhere (and is tested on its own).- The constants and helper functions (
DEFAULT_VALUES,readInteger...) are outsideuseRoomFilters: they have no state and do not need to be created on every call. - The
returnexposes only what the view uses.urlFiltersandapplyFiltersare internal details.
10.3 RoomsView refactored
In the script of src/views/RoomsView.vue, delete: DEFAULT_VALUES, VALID_SORTS, firstValue, readInteger, urlFilters, applyFilters, filterInUrl, the five filter computeds, catalog, normalize, matchesSearch, catalogEquipment, roomsWithCapacity, visibleRooms and clearFilters. Also delete const route = useRoute() and its import if nothing else uses it (the router is still needed for prepareBooking). Add in their place:
// RoomsView.vue
import { useRoomFilters } from '@/composables/useRoomFilters.js'
// (after roomsStore and storeToRefs, which do not change)
const {
floorFilter, minCapacity, requiredEquipment, sort, search,
catalog, catalogEquipment, visibleRooms, clearFilters
} = useRoomFilters(() => roomsStore.rooms)
const freeRooms = computed(() => catalog.value.filter((room) => room.available).length)
const hasResults = computed(
() => !loading.value && !error.value && visibleRooms.value.length > 0
)- The names are the usual ones, so the template (
v-model:floor="floorFilter",:rooms="visibleRooms", the "Clear filters" button) does not change. It is the same advice we have followed in every refactoring since 05-04. () => roomsStore.rooms: a getter, so that the composable follows the store when the catalogue arrives. PassingroomsStore.roomswithout a getter would not work: the store replaces the array when it loads, and the composable would be stuck forever with the initial empty array. The getter prevents that.freeRoomsandhasResultsstay in the view: they depend on the store'sloadinganderrorand decide what is rendered. They are not filtering logic.
RoomsView's script loses about eighty lines and is left focused on what belongs to the screen: coordinating the store, the composable, the selection and navigation.
- Colmena:
useAvailability
useAvailability11.1 A rule that does not exist yet
Today, the only one who knows whether a room is free at a given time is the server: when the form submits a booking that overlaps with another, the simulated API responds with a 409 overlap (05-02) and BookingView shows the translated error. The user finds out that the time was taken after filling in the whole form. And the room's spec sheet says nothing about free slots.
But the bookings store already has the information: loadBookings brings in all the centre's bookings (a member only sees their own in "My bookings" because myBookings filters them), and activeBookings discards the cancelled ones. All we need is to work out, for a room and a day, which bookings there are and which slots are left.
11.2 A new utility
To convert minutes into 'HH:MM' times (the inverse operation of toMinutes), add to the end of src/utils/dates.js:
// src/utils/dates.js: add
// Minutes since midnight → 'HH:MM' (the inverse of toMinutes)
export function toTime(minutes) {
const hours = String(Math.floor(minutes / 60)).padStart(2, '0')
return `${hours}:${String(minutes % 60).padStart(2, '0')}`
}11.3 The composable
Create src/composables/useAvailability.js:
// src/composables/useAvailability.js
// Occupancy of a room on a date, calculated from the store's bookings:
// the day's bookings, free slots within the centre's opening hours, and conflicts.
import { computed, inject, toValue } from 'vue'
import { useBookingsStore } from '@/stores/bookings.js'
import { CONFIG_KEY } from '@/keys.js'
import { toMinutes, toTime, durationHours } from '@/utils/dates.js'
const DEFAULT_HOURS = { openingHour: 8, closingHour: 20 }
// Two 'HH:MM' intervals overlap if each one starts before the other ends
export function overlap(a, b) {
return toMinutes(a.startTime) < toMinutes(b.endTime) && toMinutes(b.startTime) < toMinutes(a.endTime)
}
export function useAvailability(roomId, date) {
const bookingsStore = useBookingsStore()
const { openingHour, closingHour } = inject(CONFIG_KEY, DEFAULT_HOURS)
// Bookings that occupy the room that day, by start time (cancelled ones do not occupy it)
const dayBookings = computed(() => {
const id = toValue(roomId)
const day = toValue(date)
if (!id || !day) return []
return bookingsStore.activeBookings.filter((b) => b.roomId === id && b.date === day)
})
// Gaps between opening and closing time that no booking occupies
const freeSlots = computed(() => {
const opening = openingHour * 60
const closing = closingHour * 60
const slots = []
let from = opening // first minute not yet occupied
for (const booking of dayBookings.value) {
const start = Math.min(toMinutes(booking.startTime), closing) // nothing beyond closing time
if (start > from) slots.push({ startTime: toTime(from), endTime: toTime(start) })
from = Math.max(from, toMinutes(booking.endTime))
}
if (from < closing) slots.push({ startTime: toTime(from), endTime: toTime(closing) })
return slots
})
const busyHours = computed(() =>
dayBookings.value.reduce((total, b) => total + durationHours(b.startTime, b.endTime), 0)
)
// The first booking that clashes with the proposed time slot, or null
function conflictsWith(startTime, endTime) {
return dayBookings.value.find((b) => overlap(b, { startTime, endTime })) ?? null
}
function isFree(startTime, endTime) {
return conflictsWith(startTime, endTime) === null
}
return { dayBookings, freeSlots, busyHours, conflictsWith, isFree }
}The design decisions:
- It uses the store internally, but it is not a store. It keeps no state of its own: everything is computeds derived from
bookingsStore.activeBookings. Two components that check different days each have their ownuseAvailability, and both see the same source of truth. - It does not load data. Deciding when to request the bookings is the view's responsibility (
RoomDetailViewwill do it when it mounts). A calculation composable that also fired off requests would be harder to reuse and to test. - The centre's opening hours arrive through
inject, as inBookingForm(03-07), with a default value so that the composable works even if nobody provides them. freeSlotswalks through the bookings in order, keeping track of the first free minute (from).Math.min(..., closing)prevents a slot that "ends" after closing time if there is a later booking (one of the tests in section 12 caught it).Math.maxguards against bookings that start before opening time.overlapis exported: it is the same rule the simulated API uses, and it is a pure function that is tested on its own.conflictsWithandisFreeare functions, not computeds, because they take arguments. Since they readdayBookings, if they are called inside a computed (for example, in the form'serrors), it is recalculated when the bookings change.
The client-side check is an aid, not a guarantee. Someone else may book the same slot a second earlier, and this user's store will not know until the next load. The server still validates and
BookingViewstill shows its 409 error. It is the same rule as in 04-06: the client improves the experience, the server decides.
11.4 The room's spec sheet shows availability
In src/views/RoomDetailView.vue, add to the script:
// RoomDetailView.vue
import { ref } from 'vue' // add it to the existing 'vue' import
import { useBookingsStore } from '@/stores/bookings.js'
import { useSessionStore } from '@/stores/session.js'
import { useAvailability } from '@/composables/useAvailability.js'
import { toISODate } from '@/utils/dates.js'
const session = useSessionStore()
const bookingsStore = useBookingsStore()
if (session.active) bookingsStore.loadBookings()
const todayISO = toISODate(new Date())
const selectedDate = ref(todayISO)
// () => id: the spec sheet is reused when moving from one room to another (04-03)
const { dayBookings, freeSlots, busyHours } = useAvailability(() => id, selectedDate)And in the template, inside the room's BasePanel, after the spec sheet (</dl>):
<section v-if="room.available" class="availability" aria-labelledby="availability-title">
<h3 id="availability-title">{{ $t('availability.title') }}</h3>
<template v-if="session.active">
<label>
{{ $t('availability.date') }}
<input v-model="selectedDate" type="date" :min="todayISO" />
</label>
<p v-if="freeSlots.length === 0">{{ $t('availability.full') }}</p>
<template v-else>
<p>{{ $t('availability.freeSlots') }}:</p>
<ul class="availability__slots">
<li v-for="slot in freeSlots" :key="slot.startTime">
{{ slot.startTime }}–{{ slot.endTime }}
</li>
</ul>
</template>
<p v-if="dayBookings.length > 0" class="hint">
{{ $t('availability.bookedHours', { hours: $format.duration(busyHours) }) }}
</p>
</template>
<p v-else>{{ $t('availability.signedOut') }}</p>
</section>- Only with a session: the centre's bookings are internal information. Without a session they are neither requested nor shown.
() => id: this is the case from section 4. If you passediddirectly, when navigating from the "Polen Room" to the "Néctar Room" from "Other rooms", the spec sheet would show Polen's availability.selectedDateis a localrefof the view: this screen's own state. The composable receives it and follows it.
11.5 The form warns before submitting
In src/components/BookingForm.vue, after const form = reactive(createEmptyForm()):
// BookingForm.vue
import { useAvailability } from '@/composables/useAvailability.js'
// The user chooses the room and the day in the form itself
const { freeSlots, conflictsWith } = useAvailability(
() => form.roomId,
() => form.date
)
const freeSlotsText = computed(() =>
freeSlots.value.map((slot) => `${slot.startTime}–${slot.endTime}`).join(', ')
)In the errors computed, after the existing endTime rule:
// BookingForm.vue, inside errors, after the endTime rule
if (!result.endTime) {
const conflict = conflictsWith(form.startTime, form.endTime)
if (conflict) {
result.endTime = t('form.errors.alreadyBooked', {
start: conflict.startTime,
end: conflict.endTime
})
}
}And in the template, below the time selectors:
<p v-if="form.date && freeSlots.length > 0" class="hint">
{{ $t('form.freeSlots', { slots: freeSlotsText }) }}
</p>- One more validation rule, fitted into the usual structure: the error goes to the
endTimefield, sovisibleError('endTime'), the pending errors counter and the focus on the first error withv-focus(06-02) work without touching anything else. !result.endTime: if the time slot is already invalid (the end before the start), that message is more useful than the one about it being booked.- A design cost: since 05-04,
BookingFormhad been a presentational component that received the session as a prop and knew nothing about the stores. Now it depends on Pinia through the composable. It is a reasonable compromise (it only reads the store, never modifies it), but it has a practical consequence: any test that mountsBookingFormneeds a Pinia, for example withcreateTestingPinia(08-03). The alternative, passing availability as a prop, would force the view to know the room and the date that the user is choosing inside the form.
11.6 The new texts
Add to src/locales/en.json the freeSlots key in the form group and the alreadyBooked key in form.errors, plus a new availability group:
{
"form": {
"freeSlots": "Free that day: {slots}",
"errors": {
"alreadyBooked": "The room is already booked from {start} to {end}."
}
},
"availability": {
"title": "Availability",
"date": "Day",
"freeSlots": "Free slots",
"full": "There are no free slots left that day.",
"bookedHours": "Hours already booked: {hours}",
"signedOut": "Sign in to check availability."
}
}(The snippet only shows the new keys: merge them into the existing groups.) In the other two languages:
| Key | es.json |
ca.json |
|---|---|---|
form.freeSlots |
Libre ese día: {slots} | Lliure aquell dia: {slots} |
form.errors.alreadyBooked |
La sala ya está reservada de {start} a {end}. | La sala ja està reservada de {start} a {end}. |
availability.title |
Disponibilidad | Disponibilitat |
availability.date |
Día | Dia |
availability.freeSlots |
Franjas libres | Franges lliures |
availability.full |
No queda ninguna franja libre ese día. | No queda cap franja lliure aquell dia. |
availability.bookedHours |
Horas ya reservadas: {hours} | Hores ja reservades: {hours} |
availability.signedOut |
Inicia sesión para consultar la disponibilidad. | Inicia sessió per consultar la disponibilitat. |
- Testing the composables with
withHost
withHostIn 08-03 you created tests/withHost.js, which runs a composable inside the setup of a minimal component with the given plugins, and we announced that we would use it here. All three composables need it: useRequest registers an onScopeDispose that we want to check on unmounting, useRoomFilters uses the router and useAvailability uses Pinia and inject.
12.1 useRequest
To control the order in which responses arrive, the test's loader returns promises that the test resolves whenever it wants, with Promise.withResolvers() as in 08-02:
// src/composables/__tests__/useRequest.spec.js
import { describe, it, expect, vi } from 'vitest'
import { ref } from 'vue'
import { flushPromises } from '@vue/test-utils'
import { withHost } from '@tests/withHost.js'
import { useRequest } from '../useRequest.js'
// A loader whose responses the test resolves whenever it wants, in whatever order it wants
function createControlledLoader() {
const calls = []
const loader = vi.fn((param, { signal }) => {
const { promise, resolve, reject } = Promise.withResolvers()
calls.push({ param, signal, resolve, reject })
return promise
})
return { loader, calls }
}
describe('useRequest', () => {
it('loads on start-up and exposes data and loading state', async () => {
const { loader, calls } = createControlledLoader()
const { result } = withHost(() => useRequest(loader, '2026-10'))
expect(loader).toHaveBeenCalledWith('2026-10', { signal: expect.any(AbortSignal) })
expect(result.loading.value).toBe(true)
calls[0].resolve(['INV-2026-0141'])
await flushPromises()
expect(result.loading.value).toBe(false)
expect(result.data.value).toEqual(['INV-2026-0141'])
expect(result.error.value).toBeNull()
})
it('repeats the request when the source changes and cancels the previous one', async () => {
const { loader, calls } = createControlledLoader()
const month = ref('2026-09')
const { result } = withHost(() => useRequest(loader, month))
month.value = '2026-10'
await flushPromises()
expect(loader).toHaveBeenCalledTimes(2)
expect(calls[1].param).toBe('2026-10')
expect(calls[0].signal.aborted).toBe(true)
// Even if the first one responded late, its result does not overwrite the second one's
calls[1].resolve(['october'])
calls[0].resolve(['september'])
await flushPromises()
expect(result.data.value).toEqual(['october'])
})
it('keeps the whole error and allows retrying', async () => {
const { loader, calls } = createControlledLoader()
const { result } = withHost(() => useRequest(loader, '2026-10'))
const failure = Object.assign(new Error('No connection'), { code: 'connection' })
calls[0].reject(failure)
await flushPromises()
expect(result.error.value).toBe(failure)
expect(result.loading.value).toBe(false)
result.reload()
calls[1].resolve([])
await flushPromises()
expect(result.error.value).toBeNull()
expect(result.data.value).toEqual([])
})
it('cancels the pending request when the component unmounts', () => {
const { loader, calls } = createControlledLoader()
const { wrapper } = withHost(() => useRequest(loader, '2026-10'))
wrapper.unmount()
expect(calls[0].signal.aborted).toBe(true)
})
})- The second test reproduces the race condition on purpose: it resolves the new request before the old one. If you removed the
controller === owncheck, it would fail with['september']. - The last one uses the
wrapperthatwithHostreturns: unmounting the host destroys its scope and runs theonScopeDispose. useRequestuses neitherinjectnor the router, so it needs no plugins. Since it only depends on a scope, it could also be tested witheffectScope().run(...)andscope.stop(); withwithHostwe test it under the same conditions in which the views use it.
12.2 useRoomFilters
It needs a router. The one in tests/router.js (08-02) already has the rooms route and starts at whatever address we ask for, with its query:
// src/composables/__tests__/useRoomFilters.spec.js
import { describe, it, expect, vi } from 'vitest'
import { ref } from 'vue'
import { flushPromises } from '@vue/test-utils'
import { withHost } from '@tests/withHost.js'
import { createTestRouter } from '@tests/router.js'
import { rooms } from '@/data/rooms.js'
import { useRoomFilters } from '../useRoomFilters.js'
async function setUpFilters(initialRoute) {
const router = await createTestRouter(initialRoute)
const catalog = ref(structuredClone(rooms))
const { result } = withHost(() => useRoomFilters(catalog), { plugins: [router] })
return { filters: result, router, catalog }
}
const ids = (list) => list.map((room) => room.id)
describe('useRoomFilters', () => {
it('reads the filters from the URL and filters and sorts the catalogue', async () => {
const { filters } = await setUpFilters('/rooms?floor=2&sort=price-desc')
expect(filters.floorFilter.value).toBe(2)
expect(filters.sort.value).toBe('price-desc')
expect(ids(filters.visibleRooms.value)).toEqual(['nectar', 'celda'])
expect(filters.catalogEquipment.value).toEqual(['projector', 'videoconference', 'whiteboard'])
})
it('ignores invalid values in the URL', async () => {
const { filters } = await setUpFilters('/rooms?floor=9&capacity=-3&sort=weird')
expect(filters.floorFilter.value).toBeNull()
expect(filters.minCapacity.value).toBe(1)
expect(filters.sort.value).toBe('none')
expect(filters.visibleRooms.value).toHaveLength(5)
})
it('searches ignoring case and accents', async () => {
const { filters } = await setUpFilters('/rooms?q=NECTAR')
expect(ids(filters.visibleRooms.value)).toEqual(['nectar'])
})
it('writes to the URL only the filters that do not have their default value', async () => {
const { filters, router } = await setUpFilters('/rooms?floor=2')
filters.minCapacity.value = 8
await flushPromises()
expect(router.currentRoute.value.fullPath).toBe('/rooms?floor=2&capacity=8')
expect(ids(filters.visibleRooms.value)).toEqual(['nectar'])
})
it('clears the filters in a single navigation and keeps the floor', async () => {
const { filters, router } = await setUpFilters('/rooms?floor=1&capacity=8&sort=price-asc&q=panal')
const replace = vi.spyOn(router, 'replace')
await filters.clearFilters()
expect(replace).toHaveBeenCalledTimes(1)
expect(router.currentRoute.value.fullPath).toBe('/rooms?floor=1')
})
it('follows changes to the catalogue it receives', async () => {
const { filters, catalog } = await setUpFilters('/rooms?floor=3')
expect(ids(filters.visibleRooms.value)).toEqual(['enjambre'])
catalog.value = catalog.value.filter((room) => room.id !== 'enjambre')
expect(filters.visibleRooms.value).toEqual([])
})
})- The catalogue is a
refbelonging to the test, not the store: the composable receives the rooms as an argument, so the test needs neither Pinia nor a mocked API. That is the reward for having designedroomsas a parameter. - What is checked is where the URL ends up (
currentRoute.value.fullPath), not what was called, as we learnt in 08-02. The exception is theclearFilterstest, whose rule is precisely "a single navigation". - The last test checks that the composable reacts to its argument: it is the one that would fail if you read
toValue(rooms)once outside the computed.
These tests cover the same ground as steps 3 to 6 of the "Try it" section in 04-05, which until now we had only checked by hand.
12.3 useAvailability
It needs Pinia (for the store) and, optionally, the centre's configuration (for inject). A new Pinia in each test, and the bookings are placed in the store with $patch after mounting:
// src/composables/__tests__/useAvailability.spec.js
import { describe, it, expect } from 'vitest'
import { ref } from 'vue'
import { createPinia } from 'pinia'
import { withHost } from '@tests/withHost.js'
import { useBookingsStore } from '@/stores/bookings.js'
import { CONFIG_KEY } from '@/keys.js'
import { useAvailability, overlap } from '../useAvailability.js'
function booking(id, roomId, date, startTime, endTime, status = 'confirmed') {
return { id, roomId, date, startTime, endTime, member: 'Laura Gómez', attendees: 2,
status, extraEquipment: [], notes: '' }
}
const BOOKINGS = [
booking('r-1', 'polen', '2026-11-03', '10:00', '12:00'),
booking('r-2', 'polen', '2026-11-03', '15:00', '16:30'),
booking('r-3', 'polen', '2026-11-03', '12:00', '13:00', 'cancelled'), // does not occupy it
booking('r-4', 'nectar', '2026-11-03', '09:00', '13:00'), // another room
booking('r-5', 'polen', '2026-11-04', '08:00', '20:00') // another day
]
// Mounts the composable with a new Pinia and leaves the given bookings in the store
function setUpAvailability(roomId, date, { plugins = [] } = {}) {
const pinia = createPinia()
const { result } = withHost(() => useAvailability(roomId, date), { plugins: [pinia, ...plugins] })
useBookingsStore(pinia).$patch({
byId: Object.fromEntries(BOOKINGS.map((b) => [b.id, b])),
ids: BOOKINGS.map((b) => b.id)
})
return result
}
describe('overlap', () => {
it('tells overlaps apart from adjacent slots', () => {
const morning = { startTime: '10:00', endTime: '12:00' }
expect(overlap(morning, { startTime: '11:00', endTime: '13:00' })).toBe(true)
expect(overlap(morning, { startTime: '12:00', endTime: '13:00' })).toBe(false)
})
})
describe('useAvailability', () => {
it("calculates the day's bookings and the free slots", () => {
const availability = setUpAvailability('polen', '2026-11-03')
expect(availability.dayBookings.value.map((b) => b.id)).toEqual(['r-1', 'r-2'])
expect(availability.freeSlots.value).toEqual([
{ startTime: '08:00', endTime: '10:00' },
{ startTime: '12:00', endTime: '15:00' },
{ startTime: '16:30', endTime: '20:00' }
])
expect(availability.busyHours.value).toBe(3.5)
})
it('detects conflicts with the proposed time slot', () => {
const availability = setUpAvailability('polen', '2026-11-03')
expect(availability.conflictsWith('11:00', '13:00')?.id).toBe('r-1')
expect(availability.isFree('12:00', '13:00')).toBe(true) // the cancelled one does not count
})
it('follows the room and the date when they are reactive', () => {
const roomId = ref('polen')
const date = ref('2026-11-03')
const availability = setUpAvailability(roomId, () => date.value)
date.value = '2026-11-04'
expect(availability.freeSlots.value).toEqual([])
roomId.value = 'nectar'
date.value = '2026-11-03'
expect(availability.freeSlots.value).toEqual([
{ startTime: '08:00', endTime: '09:00' },
{ startTime: '13:00', endTime: '20:00' }
])
})
it("uses the centre's opening hours provided by the application", () => {
const shortHours = {
install: (app) => app.provide(CONFIG_KEY, { centreName: 'Colmena', openingHour: 9, closingHour: 14 })
}
const availability = setUpAvailability('polen', '2026-11-03', { plugins: [shortHours] })
expect(availability.freeSlots.value).toEqual([
{ startTime: '09:00', endTime: '10:00' },
{ startTime: '12:00', endTime: '14:00' }
])
})
})- The computeds are read directly after
$patch, withoutawait: a computed is recalculated lazily at the moment it is read. You only need to wait (nextTick,flushPromises) when what you are checking is the DOM or awatch. - The third test mixes a
refand a getter as arguments: this is the flexibility from section 4. - The last test's plugin is an object with
installthat only provides the configuration.withHosthas noprovideoption, but a one-line plugin does the same job. - The closing-time case (opening hours from 9 to 14 with a booking at 15:00) is the one that exposed the bug we fixed with
Math.min(..., closing): the first version of the composable returned a slot from 12:00 to 15:00. That is why it is worth testing the edges.
Run npm test: the new tests join those from module 8, and the RoomDetailView and DashboardBookingsView tests stay green. Then run npm run test:e2e: the complete journeys (catalogue filtered by URL, booking and cancellation) confirm that the refactoring has not changed anything visible.
- VueUse: the go-to library
VueUse is a collection of more than two hundred composables maintained by members of the Vue team, covering recurring needs: storage, events, browser sensors, timers, animation, network... Before writing a generic composable, it is worth checking whether it already exists there. It is installed with:
Four VueUse composables related to what you have already done in Colmena:
| Composable | What it does | Relationship with Colmena |
|---|---|---|
useEventListener(target, event, handler) |
Adds a listener and removes it by itself on unmounting | Replaces the onMounted/onUnmounted pair for beforeunload in BookingView |
useLocalStorage(key, initial) |
A ref synchronised with localStorage (and with other tabs) |
Could store the "Hide cancelled bookings" preference from 06-01 |
onClickOutside(element, handler) |
Calls the handler when there is a click outside an element | The same idea as our v-click-outside directive |
useDebounceFn(fn, ms) |
A version of fn that only runs once it has stopped being called for ms |
We will use it for the catalogue search in 09-07 |
13.1 useEventListener in BookingView
In 04-06, BookingView added and removed the beforeunload listener by hand. With VueUse:
// BookingView.vue: replaces the onMounted/onUnmounted for beforeunload
import { useEventListener } from '@vueuse/core'
useEventListener(window, 'beforeunload', (event) => {
if (hasUnsavedChanges()) event.preventDefault()
})Remove onMounted and onUnmounted from the vue import if you do not use them anywhere else. The listener is removed by itself when the view unmounts: there is no way of forgetting the second half of the pair.
13.2 onClickOutside versus v-click-outside
// With VueUse (we do not apply it to Colmena: for comparison only)
import { useTemplateRef } from 'vue'
import { onClickOutside } from '@vueuse/core'
const menu = useTemplateRef('menu')
onClickOutside(menu, () => (menuOpen.value = false))v-click-outside (our own directive, 06-02) |
onClickOutside (VueUse) |
|
|---|---|---|
| Declared in | The template, on the element | The script, with a template ref |
| Escape | Our own .esc modifier |
Separately (for example, with onKeyStroke('Escape', ...)) |
| Options | The ones we wrote | Elements to ignore, capture, iframes |
| Maintenance | Ours (and already tested) | The community's |
Both solve the same problem. In Colmena we keep the directive: it works, it is tested and the team knows it; replacing working code with a new dependency adds nothing. In a new project, onClickOutside would save you writing it.
13.3 When to add VueUse (and when not to)
- Yes, for generic browser needs (storage, events, size or visibility observers, system preferences): they are well tested and handle edge cases that are easy to forget.
- No, for your application's domain logic:
useRoomFiltersoruseAvailabilitydo not exist in any library, and they should stay insrc/composables/. - Cost: VueUse is ready for tree shaking, so only what you import ends up in the bundle. Even so, it is one more dependency: apply the evaluation criteria from 07-01.
- Try it
- Catalogue intact. Open
/rooms?floor=2&sort=price-desc: Néctar and Celda, in that order. Change filters, reload, use "Clear filters" and "Copy link to this search": everything behaves as in 04-05. In Vue DevTools, selectRoomsView:urlFiltersno longer appears in its state, but the computeds returned by the composable do. - Availability on the spec sheet. Sign in as Laura Gómez and open the Polen Room's spec sheet. In "My bookings" you have
r-demo-1in Polen in two days' time from 10:00 to 12:00: choose that day on the spec sheet and you will see the slots 08:00–10:00 and 12:00–20:00, and "Hours already booked: 2 hrs". - Reusing the view. With that day chosen, click "Néctar Room" under "Other rooms": the availability changes to Néctar's without losing the date. Temporarily change
() => idtoidin the call touseAvailabilityand repeat: the spec sheet says Néctar, but the availability is still Polen's. Undo the change. - Without a session. Sign out and open a spec sheet: "Sign in to check availability." appears.
- Warning in the form. As Laura, book Polen on that same day from 11:00 to 13:00: the end time field shows "The room is already booked from 10:00 to 12:00." and, when you submit, it receives the focus. Choose 12:00 to 13:00: the error disappears and the hint shows the free slots. Switch the language to Catalan: the message is translated.
- Invoices by month. Sign in as Marta Vidal (manager) and open "Invoices": October, with three invoices. Switch to September: two appear, without the table flickering. Set
ERROR_PROBABILITY = 1insrc/api/simulation.js: the translated error and "Retry" appear. Set it back. - Cancellation on leaving. Temporarily add the line
signal?.addEventListener('abort', () => console.log('Invoices: request cancelled'))at the start offetchInvoices. Open "Invoices" and, before they load, click "Profile" in the side menu: the console shows the message, becauseuseRequest'sonScopeDisposecancelled the request when the view unmounted. Also change the month twice in very quick succession: the first request is cancelled. Remove the line. - The tests.
npm testandnpm run test:e2egreen.
Common Mistakes and Tips
- Returning a
reactiveand destructuring it. Reactivity is lost without any warning. Always return an object of refs. - Reading an argument with
toValueoutside a computed or awatch. You copy the value at that instant and the composable stops reacting. CalltoValueinside the reactive function. - Passing a destructured prop to a composable without a getter (
useAvailability(id, ...)). It receives a fixed value. Use() => id. - Declaring state outside the function by accident. A
const data = ref(null)at module level turns the composable into state shared by the whole application (and, in SSR, between users). If you want shared domain state, use a store. - Calling a composable in an event handler or after an
awaitin a function of your own. Hooks andinjectcannot find the component. Call the composable insetupand use what it returns in the handler. - Forgetting the clean-up. Timers, listeners and requests must be cancelled in
onScopeDispose. A composable that works in one view can leak when that view is mounted and unmounted a hundred times. - Composables that do everything. If
useAvailabilityalso loaded bookings, displayed notifications and navigated, it would be impossible to reuse. One composable, one responsibility. - Resorting to
getCurrentInstance. There is a public API for almost everything (useRouter,useAttrs,useSlots,inject). - Tip: when a view has more than one block of logic (filters, loading, selection), try writing each block as if it were a composable even if you do not extract it yet: group its
refs,computeds and functions together. Extracting it later will be a matter of moving a block, as you have done withuseRoomFilters. - Tip: before writing a generic composable (storage, events, timers), look in VueUse.
Exercises
Exercise 1. In 01-05 we sketched useOccupancy, and RoomCard still has its own attendee logic inside it (attendees, freeSeats, full, addAttendee). Write src/composables/useOccupancy.js with the signature useOccupancy(capacity), where capacity can be a number, a ref or a getter, returning attendees, freeSeats, full, addAttendee() and removeAttendee() (without going below 0 or above the capacity). Use it in RoomCard and write its tests. Do they need withHost?
Exercise 2. RoomDetailView changes the tab's title with a watch(room, ...) (04-06). Write a composable usePageTitle(title) that receives a getter, sets document.title to `${title} · Colmena Bookings` every time it changes (if the title is empty, it does nothing) and restores the previous title when the component unmounts. Use it in RoomDetailView and test it with withHost.
Exercise 3. Several parts of the application might want the current time (the reception clock, a "your booking starts in 10 minutes" notice...), and a setInterval for each one makes no sense. Write a function createShared(composable) that returns a version of the composable in which the first component to call it creates the state inside an effectScope, the following ones receive the same state, and when the last one unmounts, the scope is stopped. Apply it to useCurrentTime from section 6.
Solutions
Solution 1.
// src/composables/useOccupancy.js
import { ref, computed, toValue } from 'vue'
export function useOccupancy(capacity) {
const attendees = ref(0)
const freeSeats = computed(() => Math.max(0, toValue(capacity) - attendees.value))
const full = computed(() => freeSeats.value === 0)
function addAttendee() {
if (!full.value) attendees.value++
}
function removeAttendee() {
if (attendees.value > 0) attendees.value--
}
return { attendees, freeSeats, full, addAttendee, removeAttendee }
}In RoomCard.vue, delete the declarations of attendees, freeSeats, full and addAttendee, and write (the room prop is destructured, hence the getter):
import { useOccupancy } from '@/composables/useOccupancy.js'
const { attendees, freeSeats, full, addAttendee, removeAttendee } = useOccupancy(() => room.capacity)The notice's watch(full, ...) and the rest of the card do not change. The tests do not need a host: useOccupancy only uses ref and computed, which work outside a component (08-03):
// src/composables/__tests__/useOccupancy.spec.js
import { describe, it, expect } from 'vitest'
import { ref } from 'vue'
import { useOccupancy } from '../useOccupancy.js'
describe('useOccupancy', () => {
it('counts seats and does not exceed the capacity', () => {
const { attendees, freeSeats, full, addAttendee } = useOccupancy(2)
addAttendee()
addAttendee()
addAttendee()
expect(attendees.value).toBe(2)
expect(freeSeats.value).toBe(0)
expect(full.value).toBe(true)
})
it('does not go below zero and follows a reactive capacity', () => {
const capacity = ref(4)
const { freeSeats, removeAttendee, attendees } = useOccupancy(capacity)
removeAttendee()
expect(attendees.value).toBe(0)
capacity.value = 8
expect(freeSeats.value).toBe(8)
})
})Solution 2.
// src/composables/usePageTitle.js
import { watchEffect, toValue, onScopeDispose } from 'vue'
export function usePageTitle(title) {
const previous = document.title
watchEffect(() => {
const text = toValue(title)
if (text) document.title = `${text} · Colmena Bookings`
})
onScopeDispose(() => {
document.title = previous
})
}In RoomDetailView.vue, replace the watch(room, ...) with usePageTitle(() => room.value?.name). The test:
// src/composables/__tests__/usePageTitle.spec.js
import { it, expect } from 'vitest'
import { ref, nextTick } from 'vue'
import { withHost } from '@tests/withHost.js'
import { usePageTitle } from '../usePageTitle.js'
it('sets the title, updates it and restores the previous one on unmounting', async () => {
document.title = 'Rooms · Colmena Bookings'
const name = ref('')
const { wrapper } = withHost(() => usePageTitle(name))
expect(document.title).toBe('Rooms · Colmena Bookings') // empty: it touches nothing
name.value = 'Polen Room'
await nextTick() // watchEffect runs before the next render
expect(document.title).toBe('Polen Room · Colmena Bookings')
wrapper.unmount()
expect(document.title).toBe('Rooms · Colmena Bookings')
})Notice that here you do need await nextTick(): unlike a computed, a watchEffect does not run on reading, but in Vue's effects queue. Also bear in mind the interaction with the router's afterEach, which sets the generic title when navigating: when going from one spec sheet to another, afterEach writes "Room details" and the watchEffect replaces it as soon as the name is available.
Solution 3.
// src/composables/shared.js
import { effectScope, onScopeDispose } from 'vue'
export function createShared(composable) {
let users = 0
let state = null
let scope = null
function release() {
users--
if (users === 0 && scope) {
scope.stop() // runs the composable's onScopeDispose callbacks (clearInterval)
scope = null
state = null
}
}
return (...args) => {
users++
if (!state) {
scope = effectScope(true) // true: a detached scope, it does not stop with the component that created it
state = scope.run(() => composable(...args))
}
onScopeDispose(release) // bound to the calling component
return state
}
}// src/composables/useCurrentTime.js
import { ref, onScopeDispose } from 'vue'
import { createShared } from './shared.js'
function useCurrentTimeInternal(intervalMs = 1000) {
const now = ref(new Date())
const timer = setInterval(() => (now.value = new Date()), intervalMs)
onScopeDispose(() => clearInterval(timer))
return { now }
}
export const useCurrentTime = createShared(useCurrentTimeInternal)Two important details: effectScope(true) creates a detached scope (without the argument, the scope would be a child of the component that called first, and when that component unmounted it would stop for everyone); and the arguments are only used on the first call, because the following ones receive the state already created. It is exactly what VueUse's createSharedComposable does.
Conclusion
A composable is a function that encapsulates logic with reactive state: it is named with use, returns an object of refs that can be destructured, accepts values, refs or getters and reads them with toValue inside its computeds and watchers, cleans up its effects with onScopeDispose and is called in the synchronous context of setup, never in a handler or after an await of your own. It solves the problems of mixins (hidden origin, collisions, implicit dependencies) with explicit functions, and leaves shared domain state where it belongs: in the stores. Colmena now has its three composables: useRequest(loader, source), which manages data, loading, errors, cancellation and retries and is used by DashboardInvoicesView with the new invoices API; useRoomFilters(rooms), which has emptied RoomsView of the URL filter logic; and useAvailability(roomId, date), which lets the spec sheet show the free slots and the form warn about an overlap before submitting. All three are tested with withHost, and the E2E tests confirm that nothing visible has changed.
Composables are the part of the Composition API where the difference between JavaScript and TypeScript is most noticeable: what type does data have in useRequest? What shape must the rooms that useRoomFilters receives have? What exactly does freeSlots return? Until now, the answer was in the comments and in your memory. In the next lesson, Vue with TypeScript, we will migrate Colmena incrementally so that the editor and the compiler know those shapes and warn about errors before anything runs.
Vue.js Course
Module 1: Introduction to Vue.js
- What Is Vue.js?
- Setting Up the Development Environment
- Creating Your First Vue Application
- Understanding the Vue Instance: Application, Components and Lifecycle
- Options API and Composition API: Two Ways to Write Components
Module 2: Vue.js Basics
- Template Syntax
- Reactivity: ref and reactive
- Data Binding
- Event Handling
- Computed Properties and Watchers
- Class and Style Bindings
- Conditional Rendering
- List Rendering
- Forms with v-model
Module 3: Vue.js Components
- Introduction to Components
- Props and Custom Events
- v-model on Your Own Components
- Slots
- Template Refs and Fallthrough Attributes
- Dynamic and Async Components
- Component Communication
Module 4: Vue Router
- Introduction to Vue Router
- Setting Up Vue Router
- Dynamic Routes
- Nested Routes
- Programmatic Navigation and Query Parameters
- Navigation Guards
Module 5: State Management with Vuex and Pinia
- Introduction to Vuex
- State, Getters, Mutations and Actions
- Vuex Modules
- Using Vuex in Components
- Advanced Vuex Patterns
- Pinia: The Recommended State Management for Vue 3
- Migrating from Vuex to Pinia
Module 6: Vue.js Directives
Module 7: Vue.js Plugins
Module 8: Testing in Vue.js
- Unit Testing with Vue Test Utils and Vitest
- Mocking Dependencies
- Testing Composables and Stores
- End-to-End Testing with Cypress
Module 9: Advanced Vue.js Concepts
- The Vue 3 Composition API in Depth: Composables and Logic Reuse
- Vue with TypeScript
- Render Functions and JSX
- Transitions and Animations
- Teleport, Suspense and Error Handling
- Server-Side Rendering (SSR) with Nuxt
- Performance Optimization
