Many values in an interface are not original data but derived data: the free seats are derived from the capacity and the attendees; the estimated price, from the hourly price and the duration; the rooms your group fits into, from the catalogue and the number of people. At other times you do not want to calculate a value, but to do something when a piece of data changes: request data from a server, save to localStorage, change the tab title. Vue has a tool for each need: computed properties (computed) for the first and watchers (watch and watchEffect) for the second. Choosing well between them is one of the skills that most clearly separates clean Vue code from convoluted code. In this lesson we will also create Colmena's simulated API and load the rooms from it, cancelling requests that have become stale.
Contents
- The problem: derived logic that is repeated and recalculated
computed: derived values with caching- Computed properties must be pure
- Writable computed properties
watch: reacting to changes with side effectswatchoptions:deep,immediateandoncewatchEffect: automatic dependencies- When they run: the
flushoption - Cleaning up effects:
onWatcherCleanup - Stopping watchers
computed,watchorwatchEffect: when to use each one- The Options API equivalent
- Case study: the simulated rooms API and the derived state of
App.vue
- The problem: derived logic that is repeated and recalculated
Look at this part of the App.vue template as it was left in the previous lesson:
<button
:disabled="!selectedRoom.available || seats.booked >= selectedRoom.capacity"
>
Book a seat
</button>
<p>
{{ matchesSearch(selectedRoom) ? 'the selected room matches' : 'the selected room does not match' }}
</p>There are two problems:
- Readability: the
:disabledcondition is business logic ("can a seat be booked?") hidden in an attribute. If you need it somewhere else, you will copy it. - Efficiency: as you saw in Template Syntax, functions called from the template run on every render, even if their data has not changed. With a search over five rooms it makes no difference; when filtering and sorting hundreds of items, it does.
computed: derived values with caching
computed: derived values with cachingA computed property declares a value that is calculated from other reactive data:
<script setup>
import { ref, reactive, computed } from 'vue'
const selectedRoom = ref({ name: 'Panal Room', capacity: 8, available: true })
const seats = reactive({ booked: 0 })
const freeSeats = computed(() => selectedRoom.value.capacity - seats.booked)
const canBook = computed(
() => selectedRoom.value.available && freeSeats.value > 0
)
</script>
<template>
<p>{{ freeSeats }} seats left</p>
<button :disabled="!canBook">Book a seat</button>
</template>computed(() => ...)takes a getter function that returns the derived value.- It returns a read-only ref (a computed ref): in the script it is read with
.value(freeSeats.value) and in the template without it. - A computed property can depend on other computed properties (
canBookusesfreeSeats). - The template now says what the condition means:
!canBook.
2.1 Caching: the big difference from a function
Wouldn't a function function canBook() { ... } do just as well? The result on screen, yes; the behaviour, no. Check it for yourself:
const freeSeatsComputed = computed(() => {
console.log('Recalculating the computed property')
return selectedRoom.value.capacity - seats.booked
})
function freeSeatsFunction() {
console.log('Running the function')
return selectedRoom.value.capacity - seats.booked
}If you use both in the template and then change a piece of data that has nothing to do with them (for example, you type in the search box), you will see that "Running the function" appears on every render, whereas "Recalculating the computed property" only appears when selectedRoom or seats.booked changes.
This is because a computed property caches its last result and only recalculates it when one of its reactive dependencies changes. Dependencies are detected just as you saw in Reactivity: ref and reactive: they are the reactive data that the function read during its last run.
flowchart LR
A["freeSeats.value is read"] --> B{"Has any dependency changed since the last calculation?"}
B -->|"No"| C["Returns the cached value (does not run the getter)"]
B -->|"Yes"| D["Runs the getter, stores the result and records the dependencies"]
D --> E["Returns the new value"]
What is more, evaluation is lazy: if nobody reads the computed property, it is not calculated.
| Aspect | Function called in the template | computed |
|---|---|---|
| When it runs | On every render of the component | Only when its dependencies change and someone reads it |
| Caching | No | Yes |
| Accepts arguments | Yes | No (it is a value, not a function) |
| Ideal use | Formatting a value it receives as an argument (formatPrice(amount)) |
Values derived from the state (freeSeats, filteredRooms) |
2.2 Only reactive data counts as a dependency
Caching has a consequence that is surprising at first:
This computed property never updates: new Date() is not reactive data, so the computed property has no dependencies and its first result stays cached for ever. For a time that moves on, you need a ref that is updated by a timer, as we did in ReceptionClock.
- Computed properties must be pure
A computed property should do nothing more than calculate and return a value. It must not:
- Modify state (neither other refs nor the very data it depends on).
- Make requests or perform any asynchronous operation (a computed property cannot wait for a promise).
- Touch the DOM, or write to
localStorageor the console (except for debugging).
A very common mistake is mutating without realising it:
// WRONG! sort() sorts the ORIGINAL array in place: it modifies the state
const roomsByPrice = computed(() => catalog.value.sort((a, b) => a.hourlyPrice - b.hourlyPrice))
// RIGHT: toSorted() (or [...array].sort()) returns a sorted copy
const roomsByPrice = computed(() => catalog.value.toSorted((a, b) => a.hourlyPrice - b.hourlyPrice))Nor should you assign to a computed property's value (freeSeats.value = 3): it is read-only and Vue will show a warning. If what you need is to "do something when a piece of data changes", it is not a computed property: it is a watcher (section 5).
Since Vue 3.4, the getter receives the previously calculated value as an argument:
computed((previous) => ...). It is useful in advanced cases (for example, returning the previous value if the new one does not meet a condition), but you will not need it often.
- Writable computed properties
By default, a computed property is read-only. If you give it an object with get and set, it becomes writable: when you assign a value to it, Vue runs the set, which must translate that value into changes to the original data.
import { ref, computed } from 'vue'
const minutes = ref(120)
const hours = computed({
get() {
return minutes.value / 60
},
set(newHours) {
minutes.value = newHours * 60
}
})
console.log(hours.value) // 2
hours.value = 3 // runs set(3) → minutes.value = 180
console.log(hours.value) // 3 (recalculated from minutes)Notice that the set stores nothing in the computed property: it modifies the source (minutes) and the computed property is recalculated from it. There is still a single source of truth.
Writable computed properties are useful for presenting a piece of data in a different form and allowing it to be edited in that form, for example with v-model in a form (02-09). Use them sparingly: if the set does a lot of things, it should probably be an ordinary function.
watch: reacting to changes with side effects
watch: reacting to changes with side effectsA watcher runs a function when a reactive source changes. Unlike a computed property, it does not return a value: it is designed for side effects. You already used one in the RoomCard draft, to record the time at which the room filled up.
import { ref, watch } from 'vue'
const search = ref('')
watch(search, (newValue, oldValue) => {
console.log(`The search has changed from "${oldValue}" to "${newValue}"`)
localStorage.setItem('lastSearch', newValue)
})- First argument: the source being watched.
- Second argument: the callback, which receives the new value and the old one.
- The callback does not run when the watcher is created, only when the source changes (unless you use
immediate, section 6).
5.1 Types of source
| Source | Example | Fires when... |
|---|---|---|
| A ref (or computed) | watch(search, ...) |
Its .value changes |
| A getter function | watch(() => seats.booked, ...) |
The value the function returns changes |
A reactive object |
watch(seats, ...) |
Any property changes, at any depth (implicit deep watching) |
| An array of sources | watch([search, () => seats.booked], ...) |
Any of them changes; the callback receives arrays of new and old values |
The most typical mistake is passing the value of a property instead of a source:
const seats = reactive({ booked: 0 })
// WRONG! seats.booked is the number 0, not something watchable (Vue warns: invalid watch source)
watch(seats.booked, (n) => console.log(n))
// RIGHT: a getter that reads the property
watch(
() => seats.booked,
(newCount, oldCount) => console.log(`Seats: ${oldCount} → ${newCount}`)
)And with several sources:
watch([search, () => seats.booked], ([newSearch, newBooked], [oldSearch]) => {
console.log(newSearch, newBooked, oldSearch)
})
watch options: deep, immediate and once
watch options: deep, immediate and onceThe third argument of watch is an options object:
6.1 deep
With a getter that returns an object, the watcher only fires if the object is replaced, not if something inside it changes:
const selectedRoom = ref({ name: 'Panal Room', equipment: ['projector'] })
// Only fires when you do selectedRoom.value = otherRoom
watch(() => selectedRoom.value, () => console.log('Another room'))
// Also fires with selectedRoom.value.equipment.push('whiteboard')
watch(() => selectedRoom.value, () => console.log('Something has changed'), { deep: true })- With a
reactiveobject as a direct source, watching is already deep by default. - Since Vue 3.5,
deepaccepts a number that limits the depth (deep: 1only looks at the top-level properties). - Deep watching traverses the entire structure on every change: with large objects it is expensive. Watch the specific property you are interested in whenever you can.
- With
deep, on internal mutations the new value and the old value are the same object (it has been modified, not replaced), so comparing them is pointless.
6.2 immediate
Runs the callback once when the watcher is created, as well as on every change. This is what you need when the effect must also be applied to the initial state, for example loading data at start-up and reloading it when a filter changes. On that first run, the old value is undefined.
6.3 once
Since Vue 3.4, once: true makes the callback run only the first time the source changes; after that the watcher stops by itself:
watchEffect: automatic dependencies
watchEffect: automatic dependencieswatchEffect runs a function immediately and runs it again whenever any reactive data it has read changes. You do not declare the source: it is inferred, as with computed properties.
import { watchEffect } from 'vue'
watchEffect(() => {
document.title = `${selectedRoom.value.name} · Colmena Bookings`
})This effect reads selectedRoom.value.name, so it runs again whenever the room or its name changes.
Differences from watch:
| Aspect | watch |
watchEffect |
|---|---|---|
| Source | Explicit | Automatic (whatever the function reads) |
| First run | Only on change (unless immediate) |
Immediate, always |
| Old value | Available | Not available |
| Ideal for | Reacting to a specific piece of data, comparing values, asynchronous effects with fine-grained control | Synchronising something external with several pieces of reactive data |
Be careful with asynchronous code: watchEffect only tracks what is read before the first await. Anything you read afterwards will not be a dependency:
watchEffect(async () => {
const room = await fetchRoom(roomId.value) // roomId IS a dependency (read before the await)
console.log(seats.booked) // seats.booked is NOT (read afterwards)
})That is why watch with its explicit source is usually clearer for asynchronous effects.
- When they run: the
flush option
flush optionWhen a piece of data changes, Vue batches the updates (you saw this with nextTick). The flush option decides at which point in that cycle a watcher's callback runs:
| Value | Timing | Use |
|---|---|---|
'pre' (default) |
Before the component's DOM is updated | Most cases |
'post' |
After the DOM is updated | You need to read the already updated DOM (measuring an element, scrolling the page to it) |
'sync' |
At the very instant of the change, without batching | Very special cases; it can affect performance |
watch(
catalog,
() => {
// The DOM already reflects the new catalogue: we can count the rendered items
console.log(document.querySelectorAll('.room-list li').length)
},
{ flush: 'post' }
)For watchEffect there are the watchPostEffect() and watchSyncEffect() shortcuts.
- Cleaning up effects:
onWatcherCleanup
onWatcherCleanupImagine a watcher that fires off a request every time a filter changes. If the user changes the filter twice in a row, there are two requests in progress. If the first one takes longer than the second, it will arrive later and overwrite the correct result with data for the previous filter. This is a race condition:
sequenceDiagram
participant U as User
participant W as watch(floorFilter)
participant A as Simulated API
U->>W: floorFilter = 1
W->>A: request A (floor 1), takes 1.2 s
U->>W: floorFilter = 2
W->>A: request B (floor 2), takes 0.4 s
A-->>W: response B: rooms on floor 2
A-->>W: response A: rooms on floor 1 (arrives late and overwrites!)
Note over W: Floor 1 is displayed with the filter set to floor 2
The solution is to clean up the previous effect before launching the next one. Since Vue 3.5, onWatcherCleanup registers a function that Vue will run just before the watcher's next run (and also when the watcher is stopped):
import { watch, onWatcherCleanup } from 'vue'
watch(floorFilter, async (floor) => {
const controller = new AbortController()
onWatcherCleanup(() => controller.abort()) // cancels this request if another one arrives
const result = await fetchRooms({ floor }, { signal: controller.signal })
// ...
})AbortControlleris the browser's standard API for cancelling asynchronous operations:fetchsupports it through thesignaloption, and our simulated API will support it too.onWatcherCleanupmust be called synchronously, before the firstawait. After theawait, Vue no longer knows which watcher it belongs to and will show a warning.
Before 3.5 (and still valid), the callback receives as its third argument an onCleanup function that does the same thing:
watch(floorFilter, async (floor, oldFloor, onCleanup) => {
const controller = new AbortController()
onCleanup(() => controller.abort())
// ...
})watchEffect also receives onCleanup as an argument of its function. Cleaning up works for any resource: cancelling requests, timers (clearTimeout), subscriptions...
- Stopping watchers
Watchers created synchronously in <script setup> stop by themselves when the component is unmounted. If you need to stop one earlier, watch and watchEffect return a stop function:
const stop = watch(
() => seats.booked,
(newCount) => {
if (newCount >= 10) {
console.log('Large group: let reception know')
stop() // we no longer need to keep watching
}
}
)Since Vue 3.5, the returned value also has pause() and resume() methods to suspend the watcher temporarily.
The only tricky situation is creating a watcher asynchronously (inside a setTimeout or after an await): that watcher is not bound to the component and will stay alive after it is unmounted. Avoid this, or stop it yourself in onUnmounted.
computed, watch or watchEffect: when to use each one
computed, watch or watchEffect: when to use each one| Need | Tool | Example in Colmena |
|---|---|---|
| Obtaining a value from others | computed |
estimatedPrice, freeRooms, roomsWithCapacity |
| Doing something when a specific piece of data changes, perhaps comparing it with the old value | watch |
Reloading rooms when floorFilter changes; recording the time at which the room filled up |
| Running an effect now and whenever any of the data it uses changes | watchEffect |
Keeping document.title in sync with the selected room |
| An asynchronous effect that must be cancelled if another change arrives | watch + onWatcherCleanup |
Cancelling the stale catalogue load |
Rule of thumb: if you can express it as computed, do so. A very common mistake is using a watch to keep a variable in sync when it could be a computed property:
// WRONG! Duplicated state maintained by hand
const estimatedPrice = ref(0)
watch([hours, selectedRoom], () => {
estimatedPrice.value = selectedRoom.value.hourlyPrice * hours.value
}, { immediate: true })
// RIGHT: a derived value
const estimatedPrice = computed(() => selectedRoom.value.hourlyPrice * hours.value)The watch version has more code, can get out of sync (if you forget a source) and briefly displays a stale value.
- The Options API equivalent
As we announced in 01-05, we show the equivalent where it adds value. In Options API code you will find:
export default {
data() {
return { hours: 2, floorFilter: null, catalog: [] }
},
computed: {
// Read-only
estimatedPrice() {
return this.selectedRoom.hourlyPrice * this.hours
},
// Writable
minutes: {
get() { return this.hours * 60 },
set(value) { this.hours = value / 60 }
}
},
watch: {
floorFilter: {
handler(floor) { this.loadRooms(floor) },
immediate: true
},
// Watching a nested property: the path as a string
'seats.booked'(newCount) { console.log(newCount) }
}
}There is also this.$watch(source, callback, options) for creating watchers from methods. watchEffect has no equivalent option.
- Case study: the simulated rooms API and the derived state of
App.vue
App.vue13.1 Creating src/api/rooms.js
In a real application, the catalogue would come from a server. To practise without setting one up, we will create a simulated API: asynchronous functions that return the data from src/data/rooms.js after a random delay and that fail every now and then. That way we will be able to see real loading states, errors and race conditions. Create the src/api/ folder and the rooms.js file:
// src/api/rooms.js
// Simulated rooms API: imitates a server with variable delay and occasional failures.
import { rooms } from '@/data/rooms.js'
const MIN_DELAY_MS = 300
const MAX_DELAY_MS = 1500
const ERROR_PROBABILITY = 0.1 // 10% of requests fail
// Promise that resolves after "ms" milliseconds and can be cancelled with an AbortSignal
function wait(ms, signal) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(new DOMException('Request cancelled', 'AbortError'))
return
}
const timer = setTimeout(resolve, ms)
signal?.addEventListener(
'abort',
() => {
clearTimeout(timer)
reject(new DOMException('Request cancelled', 'AbortError'))
},
{ once: true }
)
})
}
function randomDelay() {
return MIN_DELAY_MS + Math.random() * (MAX_DELAY_MS - MIN_DELAY_MS)
}
function failSometimes() {
if (Math.random() < ERROR_PROBABILITY) {
throw new Error('Could not connect to the Colmena server')
}
}
// Returns the catalogue (optionally, only the rooms on one floor)
export async function fetchRooms({ floor = null } = {}, { signal } = {}) {
await wait(randomDelay(), signal)
failSometimes()
const result = floor === null ? rooms : rooms.filter((room) => room.floor === floor)
return structuredClone(result) // a copy: whoever receives it can modify it without touching the data
}
// Returns a room by its id
export async function fetchRoom(id, { signal } = {}) {
await wait(randomDelay(), signal)
failSometimes()
const room = rooms.find((r) => r.id === id)
if (!room) {
throw new Error(`No room exists with the id "${id}"`)
}
return structuredClone(room)
}Let's break down the important parts:
wait(ms, signal)returns a promise that resolves after the delay. If the cancellation signal (abort) arrives, it stops the timer and rejects the promise with an error named'AbortError', the same onefetchthrows when it is cancelled. If the signal had already been aborted before it started, it rejects immediately.randomDelay()produces delays of between 0.3 and 1.5 seconds: enough for two consecutive requests to arrive out of order.failSometimes()throws an error 10% of the time. If it bothers you while developing, setERROR_PROBABILITYto0.fetchRooms({ floor }, { signal }): the first object holds the filters (withfloor = null, all of them); the second, the request options. Keeping them separate mimics real APIs.structuredClonereturns a deep copy. It solves the problem we mentioned in 02-02: whoever receives the rooms can modify them without altering the shared catalogue, just as happens with data arriving from a server.
13.2 Loading the catalogue with watch and cancellation
Now App.vue will load the catalogue from the API, filtered by floor, and reload it every time the filter changes. We will also turn the derived values into computed properties and add a price estimate. Replace the <script setup> of src/App.vue:
<script setup>
import { ref, reactive, computed, watch, watchEffect, onWatcherCleanup } from 'vue'
import ReceptionClock from './components/ReceptionClock.vue'
import RoomCard from './components/RoomCard.vue'
import { rooms } from './data/rooms.js'
import { fetchRooms } from './api/rooms.js'
// Data that does not change
const today = new Date()
const receptionNote = 'The <strong>Néctar Room</strong> closes at 18:00 today.'
const euroFormatter = new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'EUR' })
const showClock = ref(true)
// --- Catalogue loaded from the API ---
const floorFilter = ref(null) // null = all floors
const catalog = ref([])
const loading = ref(false)
const error = ref('')
async function loadRooms(floor, signal) {
loading.value = true
error.value = ''
try {
catalog.value = await fetchRooms({ floor }, { signal })
} catch (e) {
if (e.name === 'AbortError') return // a more recent request has replaced it
error.value = e.message
catalog.value = []
}
loading.value = false
}
watch(
floorFilter,
async (floor) => {
const controller = new AbortController()
onWatcherCleanup(() => controller.abort()) // synchronous: before the first await
await loadRooms(floor, controller.signal)
},
{ immediate: true } // also loads at start-up
)
const freeRooms = computed(() => catalog.value.filter((room) => room.available).length)
const catalogNames = computed(() => catalog.value.map((room) => room.name).join(', '))
// --- Selected room and seats ---
const selectedRoom = ref(rooms[0])
const seats = reactive({ booked: 0 })
const hours = ref(2)
// Writable computed property: read or change the room by its id
const selectedRoomId = computed({
get: () => selectedRoom.value.id,
set(id) {
const room = rooms.find((r) => r.id === id)
if (room) {
selectedRoom.value = room
seats.booked = 0 // changing room always resets the seats
}
}
})
const freeSeats = computed(() => selectedRoom.value.capacity - seats.booked)
const canBook = computed(() => selectedRoom.value.available && freeSeats.value > 0)
const estimatedPrice = computed(() => selectedRoom.value.hourlyPrice * hours.value)
const roomMatches = computed(() => matchesSearch(selectedRoom.value))
// Catalogue rooms that the current group fits into
const roomsWithCapacity = computed(() =>
catalog.value.filter((room) => room.capacity >= seats.booked)
)
function nextRoom() {
const index = rooms.findIndex((room) => room.id === selectedRoomId.value)
selectedRoomId.value = rooms[(index + 1) % rooms.length].id
}
function bookSeats(count) {
seats.booked += Math.min(count, freeSeats.value)
}
function releaseSeats(count) {
seats.booked = Math.max(0, seats.booked - count)
}
function onBookClick(event) {
bookSeats(event.shiftKey ? 5 : 1)
}
function cancelSeats() {
const confirmed = window.confirm(
`Cancel the ${seats.booked} seats booked in the ${selectedRoom.value.name}?`
)
if (confirmed) {
seats.booked = 0
}
}
// The tab title follows the selected room
watchEffect(() => {
document.title = `${selectedRoom.value.name} · Colmena Bookings`
})
// --- Search --- (unchanged)
const searchText = ref('')
const search = ref('')
const placeholder = 'Search by name and press Enter'
function normalize(text) {
return text.normalize('NFD').replace(/[̀-ͯ]/g, '').trim().toLowerCase()
}
function matchesSearch(room) {
return normalize(room.name).includes(normalize(search.value))
}
function applySearch() {
search.value = searchText.value
}
function clearSearch() {
searchText.value = ''
search.value = ''
}
// --- Utilities ---
function formatPrice(amount) {
return euroFormatter.format(amount)
}
function formatDate(date) {
return date.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long' })
}
function toggleClock() {
showClock.value = !showClock.value
}
</script>Let's go over the new pieces:
loadRooms(floor, signal)setsloadingtotrue, requests the rooms and stores the result or the error message. If the request was cancelled (AbortError), it exits without touching anything: a newer request is under way that has already setloadingtotrueand will take care of finishing.- The
watch(floorFilter, ...)creates anAbortControllerper run and registers its cancellation withonWatcherCleanup. IffloorFilterchanges while the request is in progress, Vue runs the clean-up (the old request is cancelled) before launching the new one. Withimmediate: true, the catalogue is loaded at start-up. The clean-up also runs if the component is unmounted. freeRoomsis no longer a ref that we modified by hand: it is now a computed property that counts the available rooms in the loaded catalogue. ThetotalRoomsconstant disappears too: the total iscatalog.length.selectedRoomIdis a writable computed property. Reading it gives the room's id; assigning it looks up the room, selects it and resets the seats.nextRoomno longer has to remember to reset: that rule lives in a single place. The room is still looked up in the local catalogue; in List Rendering we will select it from the loaded list.freeSeatsandcanBookreplace the condition that was written in the:disabled, andbookSeatsreusesfreeSeats.value.estimatedPricedepends on two sources (selectedRoomandhours) and is recalculated only when one of them changes.roomMatcheswraps the call tomatchesSearchin a computed property: the function, which takes an argument, still exists so it can be reused.roomsWithCapacityfilters without modifying the catalogue (filterreturns a new array).watchEffectkeeps the browser tab's title in sync with the selected room.formatPriceis now duplicated inApp.vueandRoomCard.vue. This is a deliberate duplication: in module 7 we will replace it with a plugin.
13.3 The template
Replace the contents of <main> (the header does not change):
<main class="content">
<p class="note" v-html="receptionNote"></p>
<button class="button" @click="toggleClock">Show/hide clock</button>
<section class="catalog">
<h2>Catalogue</h2>
<p>
<button class="button" @click="floorFilter = null">All</button>
<button class="button" @click="floorFilter = 1">Floor 1</button>
<button class="button" @click="floorFilter = 2">Floor 2</button>
<button class="button" @click="floorFilter = 3">Floor 3</button>
</p>
<p>
{{ loading ? 'Loading rooms…' : error ? `Error: ${error}` : catalogNames }}
</p>
<p><strong>{{ freeRooms }}</strong> free rooms out of {{ catalog.length }}</p>
<p>
Rooms that fit {{ seats.booked }} people:
{{ roomsWithCapacity.map((room) => room.name).join(', ') }}
</p>
</section>
<div class="search-box">
<!-- ... as before, except for the final paragraph: -->
<p>
Applied search: "{{ search }}" ·
{{ roomMatches ? 'the selected room matches' : 'the selected room does not match' }}
</p>
</div>
<section class="selection">
<h2>Selected room: {{ selectedRoom.name }}</h2>
<p>Floor {{ selectedRoom.floor }} · up to {{ selectedRoom.capacity }} people</p>
<p>Booked seats: {{ seats.booked }} / {{ selectedRoom.capacity }}</p>
<p>
Duration: {{ hours }} h
<button class="button" :disabled="hours <= 1" @click="hours--">−</button>
<button class="button" :disabled="hours >= 12" @click="hours++">+</button>
· Estimated price: <strong>{{ formatPrice(estimatedPrice) }}</strong>
</p>
<button
class="button"
:disabled="!canBook"
:title="selectedRoom.available ? 'Shift + click: books 5 seats' : 'Room under maintenance'"
@click="onBookClick"
>
Book a seat
</button>
<button class="button" :disabled="seats.booked === 0" @click="releaseSeats(1)">
Release a seat
</button>
<button class="button" :disabled="seats.booked === 0" @click="cancelSeats">
Cancel booking
</button>
<button class="button" @click="nextRoom">Next room</button>
</section>
<RoomCard />
</main>Experiment:
- When the page loads you will see "Loading rooms…" for a moment and then the names. Reload several times: every so often the simulated error will appear.
- Click "Floor 1" and "Floor 3" very quickly. Temporarily add a
console.log('Requesting floor', floor)at the start ofloadRoomsand aconsole.log(e.name)at the start of thecatch: you will see that the first request is cancelled withAbortErrorand that the final result always corresponds to the last filter clicked. To see the problem we are avoiding, comment out theonWatcherCleanupline and repeat several times: now and then you will see rooms from the wrong floor. - Book some seats and watch how the "Rooms that fit..." list changes. With 5 people, Polen and Celda disappear.
- Change the duration and the room: the estimated price is updated; the tab title changes with the room.
The catalogue status line, with two nested ternaries, is hard to read. This is exactly the problem that
v-if/v-else-if/v-elsesolve, in Conditional Rendering. And the comma-separated lists of names will become real lists withv-forin List Rendering.
Common Mistakes and Tips
- Forgetting
.valuewhen reading a computed property in the script.if (canBook)is always true (it is an object). WritecanBook.value. - Side effects in a computed property (modifying state, requests, in-place
sort()). They break the cache and can cause loops. If you need an effect, use a watcher. - Using
watchto maintain a derived variable. If the value can be calculated from others, it is a computed property. - Passing a value instead of a source to
watch.watch(seats.booked, ...)does not work; use() => seats.booked. - Expecting
watchto detect internal mutations of an object returned by a getter. You needdeep: true(or, better, to watch the specific property). - Calling
onWatcherCleanupafter anawait. It must be registered synchronously at the start of the callback. - Not ignoring
AbortErrors. A cancelled request is not an error for the user; if you display it, you will see false error messages when switching filters quickly. - Tip: in Vue DevTools you can see each component's computed properties alongside their values. If a computed property does not update when you expect it to, check whether it reads any non-reactive data (such as
new Date()or an imported constant).
Exercises
Exercise 1. In RoomCard.vue, add an occupancyPercentage computed property (attendees relative to capacity, rounded to a whole number) and another, occupancyText, that returns "Free" if it is 0, "Full" if it is 100 and "N% occupied" otherwise. Display occupancyText on the card.
Exercise 2. In App.vue, save the last floor filter chosen to localStorage and restore it at start-up, so that it is kept when the page is reloaded. Hint: localStorage stores strings; null and numbers need converting.
Exercise 3. This component is meant to display a room's name from its id using fetchRoom, but it has three problems. Find them and write a correct version with watch, immediate and cancellation.
const roomId = ref('panal')
const roomName = computed(async () => {
const room = await fetchRoom(roomId.value)
return room.name
})Solutions
Solution 1.
const occupancyPercentage = computed(() =>
Math.round((attendees.value / room.capacity) * 100)
)
const occupancyText = computed(() => {
if (occupancyPercentage.value === 0) return 'Free'
if (occupancyPercentage.value === 100) return 'Full'
return `${occupancyPercentage.value}% occupied`
})Inside a computed property's getter you can use if and several statements: it is an ordinary script function. The "single expression" rule applies only to the template. room is not reactive, but attendees is, so the computed property is recalculated when the attendees change.
Solution 2.
const savedFloor = localStorage.getItem('floorFilter')
const floorFilter = ref(savedFloor ? Number(savedFloor) : null)
watch(floorFilter, (floor) => {
if (floor === null) {
localStorage.removeItem('floorFilter')
} else {
localStorage.setItem('floorFilter', String(floor))
}
})- At start-up,
getItemreturns the saved string (for example,'2') ornullif there is nothing;Numberconverts it into a number so that the API'sroom.floor === floorcomparison works. - The new
watchis a pure side effect (saving), withoutimmediate, because at start-up there is nothing new to save. It can coexist with thewatchthat loads the rooms: each one has a single responsibility. - Frequent mistake: saving
nullwithsetItem, which converts it into the string'null'; when it is read back,Number('null')isNaN.
Solution 3. Problems: (1) a computed property cannot be asynchronous: the function returns a promise, so roomName would be a promise, not text; (2) making a request is a side effect, which is forbidden in computed properties; (3) there is no error handling or cancellation of stale requests. Correct version:
import { ref, watch, onWatcherCleanup } from 'vue'
import { fetchRoom } from '@/api/rooms.js'
const roomId = ref('panal')
const roomName = ref('')
const roomError = ref('')
watch(
roomId,
async (id) => {
const controller = new AbortController()
onWatcherCleanup(() => controller.abort())
roomError.value = ''
try {
const room = await fetchRoom(id, { signal: controller.signal })
roomName.value = room.name
} catch (e) {
if (e.name !== 'AbortError') roomError.value = e.message
}
},
{ immediate: true }
)Conclusion
Computed properties declare values derived from the state: they are recalculated only when their reactive dependencies change, they cache the result and they must be pure; with get and set they can also be writable. Watchers run side effects when data changes: watch, with an explicit source (ref, getter, reactive object or array), the old value and the deep, immediate and once options; and watchEffect, which infers its dependencies and runs immediately. You have learnt to choose when they run with flush, to clean up effects with onWatcherCleanup to avoid race conditions and to stop watchers. In Colmena Bookings you have created the simulated API src/api/rooms.js with fetchRooms() and fetchRoom(id), you load the catalogue with a watch that cancels stale requests, and you use computed to calculate the free rooms, the rooms with enough capacity and the estimated price.
So far, the appearance of elements has not depended on the state: a disabled button or a full room looks the same as the others, apart from the text. In the next lesson, Class and Style Bindings, we will use these computed properties to give RoomCard a different look depending on its state and to draw an occupancy bar.
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
