In the previous lesson you saw that Colmena's public website arrives already rendered from the server so that it appears instantly. But performance does not end with the first paint: an application like Colmena Bookings is used for hours, and what the user notices is whether it responds effortlessly to every click, every filter and every long list. Vue is fast by default (its reactivity updates only what depends on each piece of data, and its compiler optimises templates), so most of the time there is nothing to do. When there is, the golden rule is measure before optimising: every technique has a cost in complexity, and applying it where it is not needed makes the code worse without improving anything. In this lesson you will learn to measure with Lighthouse, the Core Web Vitals, the browser's Performance tab and Vue DevTools; you will review loading performance (lazy routes, async components, prefetching, images and fonts) and runtime performance (shallow reactivity, markRaw, computed stability, deep watchers, prop stability, v-memo, keys and lightweight components); you will virtualise the history of 3,000 bookings from 06-01; you will decide judiciously when to use KeepAlive; you will apply a debounce to the catalogue search in useRoomFilters; and you will check with the tests that nothing has broken. The build configuration, bundle analysis and compression are left for the next lesson.

Contents

  1. Measure before optimising
  2. The starting point: a history of 3,000 bookings
  3. Loading performance
  4. Reactivity: shallowRef, markRaw, stable computeds and watchers
  5. Rendering: stable props, v-once, v-memo, keys and lightweight components
  6. Large lists: virtualisation
  7. KeepAlive, judiciously
  8. Debouncing the search in useRoomFilters
  9. Heavy work off the main thread: Web Workers
  10. Symptom, cause and technique
  11. Checking that nothing has broken
  12. Try it

  1. Measure before optimising

1.1 What to measure: the Core Web Vitals

Google defines three core user-experience metrics, the Core Web Vitals, which have become the industry benchmark:

Metric What it measures Good What makes it worse in a Vue application
LCP (Largest Contentful Paint) When the largest element of the initial screen (an image, a headline) is painted ≤ 2.5 s Lots of JavaScript before the first paint, large images without priority, data that arrives late
INP (Interaction to Next Paint) How long the page takes to react visually to interactions (clicks, keys) ≤ 200 ms Rendering huge lists, heavy calculations in a handler, expensive watchers
CLS (Cumulative Layout Shift) How much elements "jump" while the page loads ≤ 0.1 Images without dimensions, content inserted above existing content, fonts that change the text's size

In an SPA like Colmena, the initial load happens once, so INP is usually the metric that matters most day to day; on the public website from 09-06, LCP and CLS carry more weight.

1.2 What to measure with

Tool What for How
Lighthouse (a tab in Chrome's developer tools) A complete audit of loading: metrics, diagnostics and recommendations On the production version (npm run build and npm run preview), never on npm run dev, which is not optimised. In an incognito window, so that extensions do not interfere
The Performance tab What the browser does frame by frame during an interaction: JavaScript, style calculation, layout, painting Record while you perform the slow action. Long tasks (more than 50 ms) are flagged in red; the flame chart shows which functions take them up
Vue DevTools, timeline tab Which components are rendered and updated, how many times and how long each one takes Enable performance recording and repeat the action
app.config.performance (01-04) Vue's performance marks (init, render, patch for each component) inside the Performance tab Development only

Enable Vue's marks in src/main.js, alongside the application configuration:

// src/main.js, in "1. Application configuration"
app.config.performance = import.meta.env.DEV // Vue's marks in the Performance tab (development only)

With this, when you record in the Performance tab during npm run dev, the Timings track shows a bar for each component that Vue initialises, renders or updates, with its name: you will see exactly which one is taking the time.

1.3 How to measure properly

  • Under realistic conditions. Your computer is probably much faster than a user's phone. The Performance tab lets you throttle the CPU (for example, 4 times) and the network.
  • Before and after, with the same procedure. An optimisation that does not improve the measurement is undone: it only adds complexity.
  • With realistic data. With the three demo bookings, everything is fast. The problem appears with thousands.

  1. The starting point: a history of 3,000 bookings

In 06-01 you loaded 3,000 test bookings into the simulated API to measure the effect of v-memo on a manager's history. Do it again (the code is in step 4 of its "Try it" section), sign in as Marta Vidal and open "My bookings". Since then, the list has gained a <TransitionGroup> (09-04), which we already warned would have a cost with large lists.

Record these three actions in the Performance tab, with the CPU throttled 4 times: opening "My bookings", ticking "Hide cancelled bookings" and cancelling a booking. What you will find, roughly:

Action What takes up the time
Opening "My bookings" Creating 3,000 rows: thousands of VNodes and DOM elements, and the browser's work to lay them out and paint them. On top of that, Vue makes the 3,000 booking objects reactive when it reads them
Ticking "Hide cancelled bookings" <TransitionGroup> measures the position of all the rows before and after the change (the FLIP technique): thousands of forced layout reads
Cancelling a booking Walking through the whole list again: comparing the v-memo dependencies of 3,000 rows, recalculating the computeds that filter and sort, and FLIP once more

And a clue in the Memory tab: the DOM has tens of thousands of nodes, even though only about ten bookings fit on screen. The whole lesson revolves around this case, but we will start with the application's initial load.

  1. Loading performance

3.1 Lazy routes, revisited

Since 04-02, every view except HomeView and NotFoundView has been loaded with () => import(...): each one is a separate file that is downloaded when it is visited. Review the decision with what you know now:

View Loading Why
HomeView Static It is the usual entry point: it must be in the main bundle
NotFoundView Static It must appear without waiting, even if the network fails
RoomsView, RoomDetailView, BookingView Lazy They are used almost always, but not in the first paint
DashboardView and its children, LoginView Lazy Only with (or in order to get) a session
DashboardInvoicesView Lazy Managers only: most users never download it

How to group several views in the same file, how chunks are named and how to analyse what each one contains is build configuration: you will see it in Building for Production.

3.2 Async components

defineAsyncComponent (03-06) brings the same idea to components. BuildingMap, the heaviest component in the catalogue, already uses it. The criterion for applying it: a large component (or one that drags in a large library) that is not always shown. A perfect candidate will appear in this lesson: the virtual list component from section 6, which depends on a library and is only needed by managers with more than a hundred bookings.

3.3 Prefetching what will probably be visited

Lazy loading has a downside: when "Rooms" is clicked, the user waits for RoomsView to download. That download can be brought forward when there are signs that they are going to visit it, for example when the mouse moves over the link or the link receives keyboard focus. The routes' loading functions can be called, and a dynamic import that has already resolved (or is in progress) is not repeated. Create src/router/prefetch.js:

// src/router/prefetch.js
// Downloads in advance the code of a destination's lazy views, if it is not loaded yet
export function prefetchRoute(router, destination) {
  // matched: the route's record and those of its ancestors (e.g. DashboardView and DashboardProfileView)
  for (const record of router.resolve(destination).matched) {
    const component = record.components?.default
    if (typeof component === 'function') {
      component().catch(() => {}) // if it fails, the real navigation will try again
    }
  }
}

And in AppHeader.vue's menu:

<!-- AppHeader.vue: on the "Rooms" link (the same for "My dashboard" with { name: 'dashboard-profile' }) -->
<RouterLink
  :to="{ name: 'rooms' }"
  @mouseenter="prefetchRoute(router, { name: 'rooms' })"
  @focus="prefetchRoute(router, { name: 'rooms' })"
>
  {{ $t('menu.rooms') }}
</RouterLink>
// AppHeader.vue
import { prefetchRoute } from '@/router/prefetch.js'
// router already exists in the component: const router = useRouter()
  • router.resolve(destination) works out a destination's route without navigating (04-05), and its matched contains the records of the route and of its ancestors: for dashboard-profile, that of DashboardView and that of DashboardProfileView, which are two files. Each record's component is in components.default. As long as the route has not been visited, it is the () => import(...) function; Vue Router replaces it with the component the first time it navigates to it, and from then on typeof is no longer 'function' and nothing is done. And calling the function several times before that costs nothing: the browser keeps each imported module and does not repeat the download.
  • Between the mouse entering the link and the click, hundreds of milliseconds usually pass: enough to download a view.
  • Do not prefetch everything on start-up: you would cancel out the benefit of splitting the code. Prefetch what is likely.

It is what <NuxtLink> does automatically, as you saw in 09-06.

3.4 Images

Images are usually the heaviest part of a page, and they affect all three metrics:

Attribute What for Where in Colmena
width and height The browser reserves the space before downloading it: it prevents jumps (CLS) Every image
loading="lazy" It is only downloaded when it approaches the visible area The photos on the catalogue cards
fetchpriority="high" Maximum priority: it is probably the LCP element The photo on the room's spec sheet
decoding="async" Decodes without blocking the rest of the painting Large images
srcset and sizes The browser chooses the right size for the screen If several versions of each photo are generated

In RoomCard.vue, the imageAttributes computed from 02-03 gains three attributes:

// RoomCard.vue
const imageAttributes = computed(() => ({
  src: `/img/rooms/${room.id}.webp`,
  alt: `Photo of the ${room.name}`,
  width: 400,
  height: 250,
  loading: 'lazy',
  decoding: 'async'
}))

And in RoomDetailView.vue, the spec sheet's photo, which is on the first screen:

<img
  :src="`/img/rooms/${room.id}.webp`"
  :alt="`Photo of the ${room.name}`"
  width="800"
  height="500"
  fetchpriority="high"
  class="detail__photo"
/>
/* So that the image adapts to the available width without being distorted */
.detail__photo {
  width: 100%;
  height: auto;
}

width and height in the HTML do not set the on-screen size (the CSS does that); they tell the browser the aspect ratio so that it can reserve the space. The photos have been in WebP since 02-03, a format that weighs considerably less than JPEG at the same quality.

3.5 Fonts

Colmena uses the system font stack, which is not downloaded. If a web font is ever added:

  • font-display: swap in its @font-face: the text is shown straight away with a system font and swapped when the web font arrives, instead of remaining invisible.
  • Only the weights and styles you need, in WOFF2 format.
  • Preload the main font with <link rel="preload" as="font" type="font/woff2" crossorigin> in index.html.
  • To reduce the jump when the font changes (CLS), adjust the fallback font with size-adjust or choose one with similar metrics.

  1. Reactivity: shallowRef, markRaw, stable computeds and watchers

4.1 How much deep reactivity costs

ref and reactive are deep (02-02): when you read a nested object, Vue wraps it in a Proxy, and each property that a component or a computed reads is recorded as a dependency. For five rooms, it is irrelevant. For 3,000 bookings with nine fields, it means tens of thousands of intercepted reads and recorded dependencies on every render.

shallowRef is reactive only in .value: replacing the value notifies whoever depends on it, but what is inside are plain objects, with no proxies or tracking. It is ideal for data that is replaced as a whole and never modified internally.

4.2 The catalogue: shallowRef with no other changes

In useRoomsStore, the catalogue is only modified in one way: rooms.value = await api.rooms.fetchRooms(). Nobody changes a room internally. It is the perfect case:

// src/stores/rooms.js
import { ref, shallowRef, computed } from 'vue'

const rooms = shallowRef([]) // replaced as a whole on loading; never modified internally

No other change. With five rooms the gain is small, but it is the right decision for read-only data coming from an API, and we already made it in useRequest (09-01).

4.3 The bookings: shallowRef with immutable updates

In useBookingsStore, byId contains the 3,000 bookings. But, unlike the catalogue, the store does modify bookings internally: save adds a property to byId, and the optimistic cancellation (05-07) does booking.status = 'cancelled'. With a shallowRef, those changes would notify nobody. You have to change both the declaration and the way of updating at the same time: instead of modifying, replace.

// src/stores/bookings.js
import { ref, shallowRef, computed } from 'vue'

// inside the store's setup:
const byId = shallowRef({}) // { [id]: booking }: replaced as a whole, never modified internally

// Insert or replace a booking: a new byId object
function save(booking) {
  if (!(booking.id in byId.value)) ids.value.push(booking.id)
  byId.value = { ...byId.value, [booking.id]: booking }
}

// Change a booking's status: a new booking inside a new byId
function setStatus(id, status) {
  const booking = byId.value[id]
  if (booking) byId.value = { ...byId.value, [id]: { ...booking, status } }
}

async function cancelBooking(id) {
  const booking = byId.value[id]
  if (!booking || booking.status === 'cancelled' || operations.value[id]) return

  const previousStatus = booking.status
  operations.value[id] = 'cancelling'
  setStatus(id, 'cancelled') // optimistic
  try {
    save(await api.bookings.cancelBooking(id)) // server version
  } catch (e) {
    setStatus(id, previousStatus) // rollback
    throw e
  } finally {
    delete operations.value[id]
  }
}
  • setStatus is a new internal function (it is not returned), with the same logic that the two status assignments had.
  • Copying an object with 3,000 keys ({ ...byId.value }) costs very little compared with what is saved: the list no longer has thousands of proxies or dependencies.
  • Only the reference of the modified booking changes: the other 2,999 are still the same objects. This will be key in section 5.
  • loadBookings and $reset already replaced byId as a whole, so they do not change. ids is still an ordinary ref: it is an array of strings, and push on it notifies correctly.

An important warning, which you will see in section 11: with shallowRef, any code that modifies a booking internally silently stops working. There is no error: the interface simply does not update. That is why this technique is applied with the tests green before and after.

4.4 markRaw: objects that must never be reactive

Some objects must never become reactive: instances of external libraries (a map, a text editor, a chart), classes with their own internal state, huge read-only objects. Making them reactive is costly and sometimes breaks them (their internal methods end up working with the Proxy instead of the real object). markRaw marks them so that Vue never wraps them, even if they are inside a ref or a reactive:

import { shallowRef, markRaw, onMounted } from 'vue'

const map = shallowRef(null)

onMounted(() => {
  // The library's instance, as it is, without a Proxy
  map.value = markRaw(new MapLibrary(element.value, { zoom: 18 }))
})

We already applied it without naming it: in 03-06, the components in views are in a plain object, and we warned that storing a component in a deep ref would make Vue show a warning. The solution was shallowRef or markRaw.

4.5 Stable computeds (Vue 3.4+)

Since Vue 3.4, a computed only notifies its dependants if its value changes. If hasResults in RoomsView is recalculated because the visible list changed, but it is still true, the template is not re-rendered on its account.

This only works with values that compare well (numbers, strings, booleans, or the same object). A computed that returns a new object on every calculation always "changes":

// Always "changes": a new object on every calculation, even if the values are equal
const summary = computed(() => ({
  total: bookings.value.length,
  active: activeBookings.value.length
}))

// Vue 3.4+: the function receives the previous value and can return it if nothing has changed
const stableSummary = computed((previous) => {
  const total = bookings.value.length
  const active = activeBookings.value.length
  if (previous && previous.total === total && previous.active === active) return previous
  return { total, active }
})

In practice: prefer small computeds that return simple values, and use the previous value only if you measure that a recalculated object causes unnecessary renders.

4.6 Unnecessary deep watchers

A watch with deep: true walks through the whole observed object every time it runs, to record every nested property as a dependency:

// Walks through 3,000 bookings and all their fields on every change
watch(() => bookingsStore.bookings, () => updateCounter(), { deep: true })

// Better: watch exactly the piece of data you are interested in
watch(() => bookingsStore.activeBookings.length, (active) => updateCounter(active))

Since Vue 3.5, deep also accepts a number, the maximum depth ({ deep: 1 }). In Colmena there is a deep watcher that we did not write ourselves: the $subscribe used by the persistence plugin (05-07) is a deep watcher on the store's state, which also serialises the 3,000 bookings and writes them to localStorage on every change. With byId in a shallowRef, the traversal is cheaper (there are no proxies), but the write is still there. If you measure it and it shows up in the Performance tab, the solution is to defer the writes; that is exercise 2.

  1. Rendering: stable props, v-once, v-memo, keys and lightweight components

5.1 When a child is re-rendered

A child component is re-rendered when some reactive data that it itself reads changes, or when its parent renders and passes it some different prop (Vue compares each prop with the previous one). If all its props are equal, the child does nothing. That leads to a very effective technique: pass each child props that only change when what it displays changes.

<!-- Unstable: when newBookingId changes, EVERY row receives a different prop and is rendered -->
<BookingRow v-for="booking in bookings" :key="booking.id" :booking="booking" :new-booking-id="newBookingId" />

<!-- Stable: each row receives a boolean; when newBookingId changes, only two rows change -->
<BookingRow v-for="booking in bookings" :key="booking.id" :booking="booking" :is-new="booking.id === newBookingId" />

5.2 BookingRow: the row as a lightweight component

Until now, the "My bookings" row was an <li> inside DashboardBookingsView, with a v-memo that did by hand what the previous section does automatically. We will extract the row into its own component. Create src/components/BookingRow.vue, moving the content of the <li> into its template (adapt the details to what you have in your row):

<script setup>
// src/components/BookingRow.vue
// A booking in the history. Its props only change when what it displays changes.
import StatusBadge from './StatusBadge.vue'
import BaseButton from './base/BaseButton.vue'
import { useFormat } from '@/plugins/format.js'

const { booking, roomName, cancelling = false } = defineProps({
  booking: { type: Object, required: true },
  roomName: { type: String, required: true },
  cancelling: Boolean
})

const emit = defineEmits(['cancel'])
const format = useFormat()
</script>

<template>
  <article class="booking-row" data-test="booking" :data-id="booking.id">
    <StatusBadge :status="booking.status" />
    <p class="booking-row__room">{{ roomName }}</p>
    <p>{{ format.date(booking.date) }} · {{ booking.startTime }}–{{ booking.endTime }} · {{ booking.member }}</p>
    <BaseButton
      v-if="booking.status !== 'cancelled'"
      variant="danger"
      :disabled="cancelling"
      data-test="cancel-booking"
      @click="emit('cancel', booking)"
    >
      {{ cancelling ? $t('bookings.cancelling') : $t('bookings.cancel') }}
    </BaseButton>
  </article>
</template>

Why each decision favours performance:

  • booking is an object, but thanks to section 4.3 its reference only changes when that booking changes. Cancelling a booking produces a new object for it and leaves the other 2,999 untouched: only one row receives a different prop.
  • roomName and cancelling are simple values, calculated by the parent for each row.
  • The event carries the booking (emit('cancel', booking)), so the parent can listen with @cancel="requestCancellation", the same function for every row. An inline handler inside the v-for, such as @cancel="() => requestCancellation(booking)", would create a new function per row on every render of the parent, and handlers are props too.
  • The language is no longer a problem: the row reads format.date and $t in its own render, so Vue records the language as a dependency of the row. The bug from 07-03 (untranslated rows because of a v-memo that was missing locale) cannot happen again.
  • data-test and data-id move to the row, so that the E2E test from 08-04 still finds them.

5.3 v-once and v-memo, revisited

In 06-01 you used v-once in AppFooter's legal notice and v-memo in the history's rows. In the light of what we have seen:

Directive When it still makes sense In Colmena
v-once Genuinely static content inside a component that renders often It stays in AppFooter: it costs nothing and has no risks
v-memo Lists of hundreds or thousands of DOM elements with template rows (not components) that change little, when you have measured it It is removed from the history: with BookingRow and stable props, Vue already avoids rendering the rows that do not change, with no list of dependencies to maintain by hand. And with virtualisation (section 6), there will never be more than a few dozen rows in the DOM

Removing an optimisation is also optimising: v-memo was a source of subtle bugs (you saw it with the language), and its benefit has disappeared.

5.4 Stable keys and lightweight components

  • Stable keys: each row's key is the booking's id, never the index (02-08). With indexes, when filtering or cancelling, Vue would reuse rows for different bookings and would have to update the content of all of them.
  • Lightweight components in lists: each component has a creation cost (its instance, its setup, its watchers). In a row repeated a thousand times, avoid components with lots of state of their own, watchers, timers or tooltips that create library instances. BookingRow only has props, an event and a call to useFormat (an inject).

  1. Large lists: virtualisation

6.1 The idea

Even if each row is cheap, 3,000 rows in the DOM are still 3,000 rows: memory, layout, painting and, with <TransitionGroup>, thousands of measurements. Virtualisation (or windowing) starts from an observation: only about ten bookings fit on screen. So only the visible rows (plus a few as a margin) are created in the DOM, inside a container that has the list's total height so that the scrollbar is correct. When scrolling, the rows are recycled.

flowchart LR
    subgraph Data["3,000 bookings in the store"]
        D1["0 ... 2999"]
    end
    subgraph Container["Scrolling container (fixed height)"]
        V["Only ~20 rows in the DOM<br/>(visible + margin)<br/>positioned with translateY"]
        E["An element with the total height<br/>(3,000 × estimated height)"]
    end
    D1 --> V

There are two go-to libraries in Vue:

@tanstack/vue-virtual vue-virtual-scroller
Approach Headless: it gives you positions and sizes; you write the markup Ready-made components (RecycleScroller, DynamicScroller)
Variable heights Yes, by measuring each row Yes, with DynamicScroller
Control over markup and accessibility Complete Limited to what its components expose
Chosen for Colmena Yes —

6.2 VirtualHistory

npm install @tanstack/vue-virtual

Create src/components/VirtualHistory.vue, a generic component: it receives the items and renders each one with a slot.

<script setup>
// src/components/VirtualHistory.vue
// Virtualised list: it only creates the visible rows (and a few as a margin) in the DOM
import { computed, useTemplateRef } from 'vue'
import { useVirtualizer } from '@tanstack/vue-virtual'

const { items, estimatedHeight = 88, height = '36rem' } = defineProps({
  items: { type: Array, required: true },          // each item with a unique id
  estimatedHeight: { type: Number, default: 88 },  // px per row, before measuring it
  height: { type: String, default: '36rem' }       // the container's visible height
})

const container = useTemplateRef('container')

// The options are a computed: if the number of items changes, the virtualiser finds out
const virtualizer = useVirtualizer(
  computed(() => ({
    count: items.length,
    getScrollElement: () => container.value,
    estimateSize: () => estimatedHeight,
    overscan: 6, // margin rows above and below
    getItemKey: (index) => items[index].id
  }))
)

const rows = computed(() => virtualizer.value.getVirtualItems())
const totalHeight = computed(() => virtualizer.value.getTotalSize())

// Measures each real row, for heights that do not match the estimate
function measure(element) {
  if (element) virtualizer.value.measureElement(element)
}
</script>

<template>
  <div ref="container" class="virtual-history" :style="{ height }">
    <ul class="virtual-history__list" :style="{ height: `${totalHeight}px` }">
      <li
        v-for="row in rows"
        :key="row.key"
        :ref="measure"
        :data-index="row.index"
        :aria-setsize="items.length"
        :aria-posinset="row.index + 1"
        class="virtual-history__row"
        :style="{ transform: `translateY(${row.start}px)` }"
      >
        <slot :item="items[row.index]" :index="row.index" />
      </li>
    </ul>
  </div>
</template>

<style scoped>
.virtual-history {
  overflow-y: auto; /* the container is what scrolls */
  contain: strict;  /* what happens inside does not affect the layout outside */
}

.virtual-history__list {
  position: relative;
  margin: 0;
  padding: 0;
  list-style: none;
}

.virtual-history__row {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
}
</style>

Let's analyse the pieces:

  • useVirtualizer receives the options (here, in a computed so that they follow items) and returns a ref with the virtualiser. getVirtualItems() gives the rows that must exist right now, each with its index, its key and its start position; getTotalSize(), the height of the whole list.
  • getScrollElement indicates which element scrolls: the fixed-height container. The virtualiser listens to its scroll to recalculate which rows are due.
  • translateY(row.start) places each row in its position: it is a transform, the cheapest thing to animate and reposition (09-04).
  • :ref="measure" with data-index: a function ref is called with the element every time it mounts. measureElement reads its real height (and watches it with a ResizeObserver), using data-index to know which row it is. That is how rows of different heights work, such as one with a long notice.
  • aria-setsize and aria-posinset: a screen reader only sees the twenty rows in the DOM; these attributes tell it that the list has 3,000 items and the position of each one.
  • contain: strict tells the browser that the container does not influence the layout of the rest of the page, which makes the calculations cheaper when scrolling.

6.3 DashboardBookingsView: virtual only when needed

Virtualisation has costs: the history gets its own internal scrolling, the browser's search (Ctrl+F) does not find the rows that are not in the DOM, and the <TransitionGroup> animations are lost. For a member with ten bookings it is not worth it. That is why we will only use it above a threshold. In the script of DashboardBookingsView.vue:

// DashboardBookingsView.vue
import { defineAsyncComponent } from 'vue' // add it to the 'vue' import
import BookingRow from '@/components/BookingRow.vue'

// Above this number of visible bookings, the list is virtualised
const VIRTUAL_THRESHOLD = 100

// It is only downloaded (with its library) if some history goes over the threshold
const VirtualHistory = defineAsyncComponent(() => import('@/components/VirtualHistory.vue'))

And in the template, replace the list (the <TransitionGroup> from 09-04 with its <li> and the v-memo) with the two variants:

<!-- DashboardBookingsView.vue -->
<VirtualHistory
  v-else-if="visibleBookings.length > VIRTUAL_THRESHOLD"
  :items="visibleBookings"
  class="booking-list"
>
  <template #default="{ item: booking }">
    <BookingRow
      :booking="booking"
      :room-name="roomNameById(booking.roomId)"
      :cancelling="isCancelling(booking.id)"
      :class="{ 'booking-list__new': booking.id === newBookingId }"
      @cancel="requestCancellation"
    />
  </template>
</VirtualHistory>

<TransitionGroup v-else tag="ul" name="booking" class="booking-list">
  <li v-for="booking in visibleBookings" :key="booking.id">
    <BookingRow
      :booking="booking"
      :room-name="roomNameById(booking.roomId)"
      :cancelling="isCancelling(booking.id)"
      :class="{ 'booking-list__new': booking.id === newBookingId }"
      @cancel="requestCancellation"
    />
  </li>
</TransitionGroup>
  • Two branches of the same v-if/v-else-if/v-else chain that the view already had (loading, error, empty, all cancelled...). The virtual branch goes first, with its condition.
  • The new booking's class is passed as class to BookingRow, which inherits it on its <article> (03-05). It is a simple-valued prop: it only changes on the affected rows. Adjust the selector of the .booking-list__new rule if it depended on the <li>.
  • v-memo disappears, as we decided in section 5.3.
  • <TransitionGroup> only works with lists of up to a hundred rows, where its measuring cost is imperceptible. The animations from 09-04 are kept for most users.
  • defineAsyncComponent: VirtualHistory and @tanstack/vue-virtual are only downloaded the first time a history goes over the threshold, that is, almost exclusively for managers (section 3.2).

Repeat the recording from section 2: opening "My bookings" creates about twenty rows instead of 3,000, and cancelling a booking renders only that row.

  1. KeepAlive, judiciously

<KeepAlive> (03-06) keeps hidden components in memory, so that when you come back they do not have to be created again. It is a cache, and like any cache, it trades speed for memory and the risk of stale data:

Use it when... Avoid it when...
The component has valuable interface state that the user expects to find again (a sort order, a scroll position, a half-filled form) The component is cheap to create
Creating it is expensive and it is switched often It shows data that must be refreshed on coming back (and you would have to do it in onActivated)
There are few candidates (use include and max) There are many, or they are large: memory grows with each one

Applied to Colmena:

  • The catalogue keeps it: the three views (grid, table, map) keep the table's sort order, the scroll position and the map's floor, and the user switches between them. It is exactly the case in the first row.
  • The dashboard does not need it: it might seem a good idea to wrap DashboardView's sub-screens in a <KeepAlive> so as not to re-render the history when going to the profile and back. But, after virtualisation, mounting the history costs about twenty rows, and the data comes from the store (which already keeps it). The cache would add memory and the question of when to refresh, without a measurable benefit. We are not adding it.

It is the pattern of the whole lesson: a technique is not good or bad in the abstract; it depends on what you measure in your case.

  1. Debouncing the search in useRoomFilters

8.1 Searching while typing

Since 02-04, the catalogue's search box has only applied the search when Enter is pressed. It is efficient, but users nowadays expect the results to change as they type. If RoomFilters emitted the search on every keystroke, each letter would trigger a navigation (router.replace) to update the URL, with everything that depends on the route being recalculated. What is more, browsers limit how many times per second the History API can be called, and some throw an error if it is exceeded.

The solution is debouncing: waiting for the user to stop typing for a moment (300 ms) and only then applying the search. The field's text, on the other hand, must update instantly.

sequenceDiagram
    participant U as User
    participant C as useRoomFilters
    participant R as URL (router)
    U->>C: "p" → searchText = 'p' (300 ms timer)
    U->>C: "po" → searchText = 'po' (restarts the timer)
    U->>C: "pol" ... "polen" (restarts every time)
    Note over C: 300 ms without keystrokes
    C->>R: applyFilters({ q: 'polen' }) — a single navigation
    R-->>C: urlFilters.q = 'polen' → visibleRooms is recalculated

8.2 The composable

In src/composables/useRoomFilters.js (09-01), replace the line const search = filterInUrl('q') with:

// src/composables/useRoomFilters.js
import { ref, computed, watch, toValue } from 'vue'
import { useDebounceFn } from '@vueuse/core'

const SEARCH_DELAY_MS = 300

// inside useRoomFilters, instead of const search = filterInUrl('q'):

// --- Search: the text changes with every keystroke; the URL, when typing stops ---
const searchText = ref(urlFilters.value.q)
const writeSearch = useDebounceFn((text) => applyFilters({ q: text }), SEARCH_DELAY_MS)

const search = computed({
  get: () => searchText.value,
  set: (text) => {
    searchText.value = text
    writeSearch(text)
  }
})

// If the URL's search changes by another route (Back, a link), the URL wins
watch(
  () => urlFilters.value.q,
  (q) => {
    if (!writeSearch.isPending.value) searchText.value = q
  }
)

In visibleRooms, filter by the applied search (the one in the URL), not by the one being typed:

const text = normalize(urlFilters.value.q) // previously: normalize(search.value)

And in clearFilters, cancel a pending search before clearing:

function clearFilters() {
  writeSearch.cancel() // a pending search must not undo the clearing
  searchText.value = ''
  return applyFilters({ capacity: 1, equipment: '', sort: 'none', q: '' })
}

The decisions:

  • Two values for the search: searchText, what has been typed (what search returns and the field displays), and urlFilters.value.q, the applied search (the one that filters and the one that is shared in the link). Separating them is what lets the field respond instantly while the rest waits.
  • useDebounceFn from VueUse (09-01) returns a version of the function that only runs once it has stopped being called for 300 ms. In current versions of VueUse, the returned function also has cancel(), flush() and isPending.
  • The URL watch syncs the field when the search changes from outside (the Back button, a shared link). isPending prevents a navigation in progress from overwriting what the user is typing at that moment.
  • clearFilters cancels anything pending: if the user types and clicks "Clear filters" before 300 ms have passed, the typed search must not reappear afterwards.
  • The rest of the filters do not change: they are buttons, and each click is a decision, not a burst.

8.3 RoomFilters searches while typing

In RoomFilters.vue (03-03), the search box no longer needs its local copy or the Enter key, because the delay is handled by the composable. Delete searchText, its watch and applySearch, and connect the field directly to the model:

<!-- RoomFilters.vue: the search box -->
<input
  id="search"
  v-model="search"
  type="search"
  placeholder="Search by name"
  @keyup.esc="search = ''"
/>
<button class="button" :disabled="search === ''" @click="search = ''">Clear</button>

Notice how the responsibilities are divided: RoomFilters is a presentational component that emits every change; useRoomFilters decides when that change turns into a navigation. If another component used the composable tomorrow, it would get the debounce without doing anything.

8.4 Testing the debounce

Add to src/composables/__tests__/useRoomFilters.spec.js (with afterEach in the Vitest import) a block with fake timers (08-02):

describe('useRoomFilters: searching while typing', () => {
  afterEach(() => {
    vi.useRealTimers()
  })

  it('shows the text instantly and applies it when typing stops', async () => {
    vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
    const { filters, router } = await setUpFilters('/rooms')

    filters.search.value = 'po'
    filters.search.value = 'polen'
    expect(filters.search.value).toBe('polen')           // the field, instantly
    expect(filters.visibleRooms.value).toHaveLength(5)   // the filtering, not yet
    expect(router.currentRoute.value.fullPath).toBe('/rooms')

    await vi.advanceTimersByTimeAsync(300)
    await flushPromises()

    expect(router.currentRoute.value.fullPath).toBe('/rooms?q=polen') // a single navigation
    expect(ids(filters.visibleRooms.value)).toEqual(['polen'])
  })

  it('clearFilters cancels the pending search', async () => {
    vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
    const { filters, router } = await setUpFilters('/rooms?floor=1')

    filters.search.value = 'panal'
    await filters.clearFilters()
    await vi.advanceTimersByTimeAsync(300)
    await flushPromises()

    expect(filters.search.value).toBe('')
    expect(router.currentRoute.value.fullPath).toBe('/rooms?floor=1')
  })

  it('follows the URL when it changes by another route', async () => {
    const { filters, router } = await setUpFilters('/rooms?q=nectar')
    await router.replace('/rooms?q=celda')
    expect(filters.search.value).toBe('celda')
  })
})
  • toFake: ['setTimeout', 'clearTimeout'] fakes only the timers that the debounce uses. If all of them were faked, flushPromises (which waits with its own timer) would never finish.
  • advanceTimersByTimeAsync moves the fake clock forward and lets the intermediate promises, such as the navigation, resolve.
  • The six tests from 09-01 still pass: searching via the URL (/rooms?q=NECTAR) works just the same.

  1. Heavy work off the main thread: Web Workers

All of the page's JavaScript, Vue included, runs on a single thread, the same one that paints and responds to clicks. A calculation that takes 300 ms freezes the interface for 300 ms, and that is what INP measures. If a calculation is unavoidably heavy (an annual occupancy report over tens of thousands of bookings, processing an imported file, compressing an image), it can be run in a Web Worker, a separate thread without access to the DOM that communicates with the page through messages. Vite supports them with a standard syntax:

// Create the worker: Vite bundles it as a separate file
const worker = new Worker(new URL('./report.worker.js', import.meta.url), { type: 'module' })
worker.postMessage({ bookings: structuredClone(bookingsStore.bookings) })
worker.onmessage = (event) => {
  report.value = event.data
}

In Colmena there is currently no calculation that justifies one: the computeds' filters, sorts and sums take milliseconds even with 3,000 bookings. Before resorting to a worker, check in the Performance tab that the time really is spent in your calculation and not in rendering (which a worker cannot do). Exercise 3 suggests one for you.

  1. Symptom, cause and technique

This table sums up the lesson as a diagnostic guide. Always start with the first column: what you observe when measuring.

Symptom Likely cause Technique
The first load is slow (high LCP in Lighthouse) Too much JavaScript in the main bundle; main image without priority Lazy routes and components; fetchpriority="high"; bundle analysis (10-01)
When a link is clicked there is a pause before the screen appears The lazy view is being downloaded at that moment Prefetching on hover or focus (prefetchRoute)
The page "jumps" while loading (CLS) Images without dimensions; fonts that change the size; content inserted above width/height; font-display and adjusted fallback fonts; reserving space
The images further down delay the ones at the top They are all downloaded at once loading="lazy" on the ones not on the first screen
Opening a screen with a long list is slow Thousands of elements in the DOM Virtualisation
An interaction is slow (high INP) and "Recalculate Style"/"Layout" dominates in Performance Thousands of nodes; forced measurements (<TransitionGroup> with large lists) Virtualisation; animating only transform/opacity; not animating huge lists
An interaction is slow and Vue DevTools shows many components updating Unstable props (new objects or functions on every render, values shared by every row) Simple props calculated per item; emitting the item in the event; row components
A lot of time spent in reactivity (proxies, dependencies) with large data Deep reactivity on data that is not modified internally shallowRef with immutable updates; markRaw for external objects
A watcher runs often and is slow deep: true on large structures Watching the specific piece of data; deep with a depth (3.5+)
Each keystroke in a search box triggers expensive work Navigation or filtering on every key Debounce
A calculation freezes the interface even though the DOM is small Heavy JavaScript on the main thread Web Worker
Returning to a screen loses its state or is slow to rebuild The component is destroyed on leaving KeepAlive with include and max, if the state is worth it

  1. Checking that nothing has broken

The optimisations in this lesson change how Colmena works internally without changing what it does. It is exactly the kind of change that module 8's safety net of tests must watch over. Run npm test and npm run test:e2e, and pay attention to what fails, because each failure tells you something:

  1. DashboardBookingsView.spec.js, "reflects changes in the store and overridden getters" (08-03). The test did bookingsStore.byId['r-demo-1'].status = 'cancelled' and expected to see the "Cancelled" badge. Now it fails: it is the warning from section 4.3 come true, an internal modification that notifies nobody. The test must update the state the way the store now does, by replacing:
// DashboardBookingsView.spec.js
const previous = bookingsStore.byId['r-demo-1']
bookingsStore.byId = { ...bookingsStore.byId, 'r-demo-1': { ...previous, status: 'cancelled' } }
  1. The withBookings helper in the store tests (08-03) used $patch with an object. The tests still pass, but by chance: with an object, $patch merges the new byId into the existing one by modifying it internally, and the interface would not have found out. Change it to a direct assignment, which expresses the intention:
function withBookings(bookingsStore, list) {
  bookingsStore.byId = Object.fromEntries(list.map((b) => [b.id, b]))
  bookingsStore.ids = list.map((b) => b.id)
}

Make the same change in setUpAvailability, in the useAvailability tests (09-01).

  1. The E2E tests stay green: data-test="booking" and data-id are now on BookingRow's <article>, and Cypress searches the whole document; the booking journey uses an empty database, so it never reaches the virtualisation threshold.

  2. The list's unit tests (.booking-list li) still find the rows: the <li> now contains the <article>, and its texts and badges are inside it.

A final warning: Vue Test Utils runs in jsdom, which does not calculate layout. A virtualised component mounted in a unit test renders no rows at all, because its container "measures" 0 pixels. To test the virtual branch, use an E2E test in a real browser, or check in the unit test only what does not depend on layout (for example, that VirtualHistory is chosen above the threshold).

  1. Try it

  1. Vue's marks. With npm run dev, open the Performance tab, record while you change a catalogue filter and look for the components' bars (<RoomsView>, <RoomCard>...) in the Timings track.
  2. Lighthouse. Run npm run build and npm run preview, open the home page in an incognito window and run Lighthouse in mobile mode. Note down LCP and CLS. Open a room's spec sheet and repeat: the photo with fetchpriority="high" and dimensions should be the LCP and cause no jumps.
  3. Prefetching. In the Network tab, filter by "View", load the home page and move the mouse over "Rooms" without clicking: RoomsView is downloaded at that moment. When you click, the screen appears without any wait.
  4. The large history. Load the 3,000 test bookings (06-01), sign in as Marta Vidal and open "My bookings". Inspect the DOM: about twenty rows inside a <ul> several hundred thousand pixels high. Scroll: the rows are recycled. In the Network tab, check that VirtualHistory and the library have only been downloaded now.
  5. Before and after. With the CPU throttled 4 times, record opening "My bookings" and cancelling a booking, and compare it with what you measured in section 2. In Vue DevTools, when cancelling, only one BookingRow is updated.
  6. Few bookings. Sign in as Laura Gómez (with the demo data): her history is short, it is shown without virtualisation and the rows are still animated when cancelled bookings are hidden.
  7. Search. In the catalogue, type "polen" quickly: the field responds with every letter and the list and the URL change only once, when you stop typing. Press Back after a search: the field shows the previous search.
  8. The tests. Apply the changes from section 11 and run npm test and npm run test:e2e: everything green. When you have finished, delete colmena-api-bookings and colmena-cache-bookings from Local Storage to go back to the demo data.

Common Mistakes and Tips

  • Optimising without measuring. You add complexity without knowing whether you are improving anything. Measure, apply a technique, measure again.
  • Measuring in npm run dev. Development mode includes checks, warnings and unminified code. Loading metrics, always on the production version.
  • Using shallowRef and still modifying internally. The interface stops updating without any error. If you choose shallowRef, every update must replace the value.
  • Passing shared values (:new-booking-id="newBookingId") or inline functions to each item in a list. Any change renders every row. Calculate a simple value per item.
  • Virtualising small lists. You lose the browser's search, the animations and some accessibility in exchange for nothing. Use a threshold.
  • Prefetching everything on start-up. It cancels out code splitting. Prefetch what is likely, when there is a sign.
  • Images without width and height. They cause content jumps even if everything else is perfect.
  • KeepAlive by default on every view. It is a cache: memory and possibly stale data. Use it where the interface state is worth it.
  • Tip: keep your measurements (a Lighthouse screenshot, the duration of a task in Performance) alongside the change that prompted them, in the description of the commit or the pull request. In six months' time, you will know why each optimisation exists and be able to check whether it is still needed.

Exercises

Exercise 1. Apply prefetching to the catalogue cards: when the mouse moves over the link on a room's name in RoomCard, prefetch the room-detail view. Check in the Network tab that the view is downloaded only once, even if you move the mouse over several cards.

Exercise 2. The persistence plugin writes to localStorage on every state change. With 3,000 bookings, cancelling one produces a complete serialisation at that very instant. Modify it so that the write is deferred by 200 ms and grouped if several changes arrive in a row, without losing data if the user closes the tab just afterwards (hint: the pagehide event). Adapt the tests in persistence.spec.js, which expected the write to be immediate.

Exercise 3. Write a Web Worker, src/workers/occupancy.worker.js, that receives a list of bookings and returns, for each room, the hours booked (active) in the given year. Use it from a composable useOccupancyReport(bookings, year) that returns report and calculating, and that terminates the worker when the component unmounts.

Solutions

Solution 1. In RoomCard.vue:

import { useRouter } from 'vue-router'
import { prefetchRoute } from '@/router/prefetch.js'

const router = useRouter()
<RouterLink
  :to="{ name: 'room-detail', params: { id: room.id } }"
  class="card__link"
  data-test="spec-sheet-link"
  @mouseenter="prefetchRoute(router, { name: 'room-detail', params: { id: room.id } })"
  @focus="prefetchRoute(router, { name: 'room-detail', params: { id: room.id } })"
>

router.resolve needs the route's params, which is why the id is passed. The view is the same for every room (/rooms/:id), so the first card downloads it and the others trigger no new download: prefetchRoute calls the import function again, but the browser already has that module (or is downloading it) and does not request it again. After the first visit to a spec sheet, Vue Router has replaced the function with the component and prefetchRoute does not even call it. Bear in mind that RoomCard is tested with RouterLinkStub when there is no router (08-01): useRouter() will return undefined in those tests, so guard the call (router && prefetchRoute(router, ...)) or mount the card with the test router.

Solution 2.

// src/stores/plugins/persistence.js (excerpt: replaces step 2)
const SAVE_DELAY_MS = 200

let pending = null

function saveNow() {
  clearTimeout(pending)
  pending = null
  const data = Object.fromEntries(fields.map((field) => [field, store.$state[field]]))
  storage.setItem(key, JSON.stringify(data))
}

store.$subscribe(
  () => {
    clearTimeout(pending)
    pending = setTimeout(saveNow, SAVE_DELAY_MS)
  },
  { detached: true }
)

// If the page is closed or hidden with a write pending, it is done right away
window.addEventListener('pagehide', () => {
  if (pending) saveNow()
})

In persistence.spec.js, the tests "saves the session in sessionStorage when it changes" and "saves only byId and ids from the bookings" need fake timers: vi.useFakeTimers() at the start of each one, vi.advanceTimersByTime(200) before reading the storage, and vi.useRealTimers() in an afterEach. Add one more test: after a change, without moving the clock forward, window.dispatchEvent(new Event('pagehide')) must leave the data saved. pagehide is more reliable than beforeunload for this (it is also emitted when the tab is closed on mobile devices, and it does not stop the browser from keeping the page in its back/forward cache).

Solution 3.

// src/workers/occupancy.worker.js
import { durationHours } from '@/utils/dates.js'

self.onmessage = (event) => {
  const { bookings, year } = event.data
  const hoursByRoom = {}
  for (const booking of bookings) {
    if (booking.status === 'cancelled' || !booking.date.startsWith(`${year}-`)) continue
    hoursByRoom[booking.roomId] = (hoursByRoom[booking.roomId] ?? 0) + durationHours(booking.startTime, booking.endTime)
  }
  self.postMessage(hoursByRoom)
}
// src/composables/useOccupancyReport.js
import { shallowRef, ref, watch, toValue, onScopeDispose } from 'vue'

export function useOccupancyReport(bookings, year) {
  const report = shallowRef(null)
  const calculating = ref(false)
  const worker = new Worker(new URL('../workers/occupancy.worker.js', import.meta.url), { type: 'module' })

  worker.onmessage = (event) => {
    report.value = event.data
    calculating.value = false
  }

  watch(
    () => [toValue(bookings), toValue(year)],
    ([list, chosenYear]) => {
      calculating.value = true
      // structuredClone: messages do not accept reactive proxies
      worker.postMessage({ bookings: structuredClone(list), year: chosenYear })
    },
    { immediate: true }
  )

  onScopeDispose(() => worker.terminate())

  return { report, calculating }
}

The composable follows the conventions from 09-01: arguments that can be refs or getters (useOccupancyReport(() => bookingsStore.bookings, 2027)), refs in the return value and clean-up with onScopeDispose. structuredClone turns the data into plain objects before sending it (with byId in a shallowRef, the bookings already are, but the array the getter returns may be reactive). The worker imports durationHours like any other module: Vite bundles it separately. If two requests arrive in a row, the worker processes them in order and the last response is the one that remains.

Conclusion

Optimising starts with measuring: Lighthouse and the Core Web Vitals (LCP, INP, CLS) for loading and experience, the Performance tab and the app.config.performance marks to see where the time goes, and Vue DevTools to find out which components update. With those measurements, you have applied to Colmena Bookings loading techniques (lazy routes and components, prefetchRoute on hover or focus, images with dimensions, loading="lazy" and fetchpriority) and runtime techniques: shallowRef in the catalogue and in the bookings, with immutable updates via setStatus; markRaw for external objects; stable computeds; watchers without unnecessary deep; BookingRow with stable props, which has made 06-01's v-memo unnecessary; VirtualHistory with @tanstack/vue-virtual, loaded asynchronously and used only above a hundred bookings; KeepAlive where the state is worth it and not where it would only add memory; and a debounce in useRoomFilters' search, which now filters while you type without one navigation per key. The tests have confirmed that the behaviour has not changed, and one of them has caught precisely the risk that shallowRef introduces.

Everything measured in this lesson about loading depends on a step we have taken so far without examining it: npm run build. What Vite does when building, how files are split and named, how to analyse what each part of the bundle contains, how the environment variables for each mode are configured and how the result is compressed are the decisions that turn this code into an application ready to publish, and we will study them in Building for Production.

New edition · October 2026

Vue.js Course

Module 1: Introduction to Vue.js

Module 2: Vue.js Basics

Module 3: Vue.js Components

Module 4: Vue Router

Module 5: State Management with Vuex and Pinia

Module 6: Vue.js Directives

Module 7: Vue.js Plugins

Module 8: Testing in Vue.js

Module 9: Advanced Vue.js Concepts

Module 10: Building and Deploying Vue.js Applications

Module 11: Real-World Vue.js Projects

© Copyright 2026. All rights reserved