Until now, each Colmena component has always appeared in the same place in the template: we write <RoomList> and there is RoomList. But many interfaces need to decide which component is rendered depending on the state: tabs, multi-step wizards, interchangeable panels or, in our case, different ways of viewing the same catalogue. Vue solves this with the special <component :is> element. When you switch components, the previous one is destroyed and loses its state, unless you wrap it in <KeepAlive>, which keeps it in a cache. And if one of those components is heavy, there is no point downloading it until the user asks for it: async components (defineAsyncComponent) are loaded on demand, and Vite automatically splits them out into separate files. In this lesson we will give Colmena's catalogue a "Grid / Table / Map" view switcher, with a building map that is only downloaded when it is needed.
Contents
- Choosing the component at runtime
<component :is>with imported components<component :is>with HTML elements- Tabs: what happens when you switch components
<KeepAlive>: preserving state- Controlling the cache:
include,excludeandmax onActivatedandonDeactivated- Async components with
defineAsyncComponent - Loading and error states,
delayandtimeout - How Vite splits the code
- Case study: the catalogue's view switcher
- Choosing the component at runtime
Suppose the catalogue can be displayed in three ways, each in its own component. With what you already know, you would write a chain of v-ifs:
<GridView v-if="currentView === 'grid'" :rooms @select="selectRoom" />
<TableView v-else-if="currentView === 'table'" :rooms @select="selectRoom" />
<BuildingMap v-else :rooms @select="selectRoom" />It works, but it repeats the same props and events in every branch, and every new view requires another branch. If the three components share the same interface (the same props, the same events), the natural thing is to write the tag once and decide the component with a variable.
<component :is> with imported components
<component :is> with imported componentsThe special <component> element renders whatever component you specify in its is prop:
<script setup>
import { ref } from 'vue'
import GridView from './components/catalog/GridView.vue'
import TableView from './components/catalog/TableView.vue'
// An ordinary (non-reactive) object that maps each key to its component
const views = {
grid: GridView,
table: TableView
}
// Only the chosen key is reactive
const currentView = ref('grid')
</script>
<template>
<button @click="currentView = 'grid'">Grid</button>
<button @click="currentView = 'table'">Table</button>
<component :is="views[currentView]" :rooms="visibleRooms" @select="selectRoom" />
</template>:isreceives the component object, the one you get when you import it. In<script setup>, passing the name as a string (:is="'TableView'") does not work: strings only work with components registered globally or in the Options API'scomponentsoption, and we saw in 03-01 that in Colmena we register locally.- The props and events you write on
<component>are passed to whichever component is active. That is why all the interchangeable components should share an interface. v-modelalso works on<component :is>.
Notice the design: the components are in an ordinary object, and the reactive state is only the key ('grid'). If you stored the component itself inside a ref (const view = ref(TableView)), Vue would turn it into a reactive object, which is pointless and expensive, and it would show a warning in the console. If you ever need to store a component in reactive state, use shallowRef (which you saw in 02-02) or markRaw.
<component :is> with HTML elements
<component :is> with HTML elementsis also accepts the name of an HTML element as a string. This is useful for components that must render one tag or another depending on the context, for example a heading's level:
<!-- SectionTitle.vue -->
<script setup>
const { level = 2 } = defineProps({
level: { type: Number, validator: (n) => n >= 1 && n <= 6 }
})
</script>
<template>
<component :is="`h${level}`" class="section-title">
<slot></slot>
</component>
</template><SectionTitle :level="3">Bookings created in this session</SectionTitle>
<!-- Result: <h3 class="section-title">Bookings created in this session</h3> -->Another classic case: a link that is rendered as an <a> or as a <button> depending on whether or not it has an href (:is="href ? 'a' : 'button'").
- Tabs: what happens when you switch components
When currentView changes, Vue unmounts the previous component (its onUnmounted runs and its state is destroyed) and mounts the new one from scratch. This is exactly what happens with v-if.
Check it with the example from section 2: if the table had its own column sorting (local state) and the user sorted it by price, on switching to the grid and coming back, the table would appear sorted by name again, scrolled back to the top. The same would happen in the grid with each RoomCard's attendee counters: they would be lost.
For tabs, this is often unacceptable: the user expects to find each tab as they left it.
<KeepAlive>: preserving state
<KeepAlive>: preserving state<KeepAlive> is a built-in component that, instead of destroying the component that is leaving, deactivates it and stores it in a cache. When you come back, it reactivates it with all its state intact:
<KeepAlive>
<component :is="views[currentView]" :rooms="visibleRooms" @select="selectRoom" />
</KeepAlive>stateDiagram-v2
[*] --> Active: first mount
Active --> Deactivated: the view is switched
Deactivated --> Active: the view is shown again
note right of Deactivated
In the cache: its state is preserved,
its elements leave the document
end note
Deactivated --> [*]: evicted from the cache (max) or KeepAlive is unmounted
Important details:
<KeepAlive>must wrap a single active component at a time (a<component :is>, or several components in av-if/v-elsechain).- The cache lives as long as
KeepAliveis mounted. If the<KeepAlive>itself is inside av-ifthat becomes false, it is destroyed along with its whole cache. If you want the content to be able to hide without losing the cache, put the condition inside:<KeepAlive><component v-if="hasData" :is="..." /></KeepAlive>. When the condition is false, the component is deactivated and stored, instead of being destroyed. - A deactivated component still exists: if it has timers or subscriptions, they keep running unless you pause them (section 7).
- Controlling the cache:
include, exclude and max
include, exclude and maxBy default, KeepAlive caches every component that passes through it. You can limit this:
| Prop | What it does | Example |
|---|---|---|
include |
Only caches the components whose name matches | include="TableView,BuildingMap" |
exclude |
Caches all of them except those that match | exclude="GridView" |
max |
Maximum number of cached instances; when it is exceeded, the least recently used one is discarded (the LRU algorithm, Least Recently Used) | :max="3" |
include and exclude accept a string with comma-separated names, a regular expression (:include="/View$/") or an array (:include="['TableView', 'BuildingMap']"). The name of a component with <script setup> is inferred from the file name (TableView.vue → TableView), so you do not have to declare it. If you ever need a different name, you can set it with defineOptions({ name: 'AnotherName' }).
max is important in applications with many tabs or views: each cached instance takes up memory with its state and its element tree.
onActivated and onDeactivated
onActivated and onDeactivatedA component kept by KeepAlive is neither unmounted nor mounted again when the view changes, so onMounted and onUnmounted are no use for detecting those changes. That is what the two lifecycle hooks we mentioned in Understanding the Vue Instance: Application, Components and Lifecycle are for:
import { onActivated, onDeactivated } from 'vue'
onActivated(() => {
// Runs on the first mount and every time the component comes back from the cache
})
onDeactivated(() => {
// Runs every time the component goes into the cache, and also when it is unmounted
})Typical uses:
| Hook | What for |
|---|---|
onActivated |
Refreshing data that may have changed while it was hidden; restoring the scroll position; resuming timers |
onDeactivated |
Pausing timers, animations or videos; cancelling requests in progress |
A situation we will meet in the case study: browsers reset the scroll position of an element when it is taken out of the document. KeepAlive preserves the component's state (its refs), but a container's scroll position is not Vue state: you have to save it and restore it in onActivated.
- Async components with
defineAsyncComponent
defineAsyncComponentAll the components you import with import X from '...' (a static import) are part of the JavaScript bundle that the browser downloads when the application opens. If a component is large and the user may never use it, that is wasteful: it delays the initial load for everyone.
JavaScript has a dynamic import, import('./path.js'), which is a function that downloads the module when it runs and returns a promise. Vue takes advantage of it with defineAsyncComponent:
import { defineAsyncComponent } from 'vue'
const BuildingMap = defineAsyncComponent(() =>
import('./components/catalog/BuildingMap.vue')
)BuildingMapis now a "wrapper" component that is used exactly like an ordinary one:<BuildingMap :rooms />or inside<component :is>.- The first time it is rendered, the wrapper runs the function, downloads the real component and, when it arrives, renders it, passing it the props, events and slots it had received.
- On subsequent occasions, the component has already been downloaded and is rendered instantly.
- While it is downloading, by default nothing is rendered.
- Loading and error states,
delay and timeout
delay and timeoutA download can be slow or fail. defineAsyncComponent accepts an options object to handle both cases:
const BuildingMap = defineAsyncComponent({
// The function that loads the component (required)
loader: () => import('./components/catalog/BuildingMap.vue'),
// Component shown while it is loading
loadingComponent: MapLoading,
// Wait before showing it (ms). Default: 200
delay: 200,
// Component shown if loading fails (it receives the "error" prop)
errorComponent: MapError,
// If it takes longer than this (ms), it is treated as an error. Default: no limit
timeout: 10000,
// Retries in the event of network failures
onError(error, retry, fail, attempts) {
if (attempts <= 3) {
retry()
} else {
fail()
}
}
})| Option | What it is for | Detail |
|---|---|---|
loader |
Loading the component | A function that returns the import() promise |
loadingComponent |
Telling the user that something is on its way | It must be a static component (already downloaded) |
delay |
Avoiding a flash of "Loading..." | If loading takes less than delay, the indicator is never seen |
errorComponent |
Showing a helpful message if it fails | It receives the error prop with the error that occurred |
timeout |
Not waiting forever | When it is exceeded, the error component is shown |
onError |
Retrying after a one-off failure | It receives functions to retry or give up, and the number of attempts |
Async components also integrate with <Suspense>, a built-in component that coordinates several asynchronous loads in a tree and shows a single loading state for all of them. It is a feature still marked as experimental, which we will study in Teleport, Suspense and Error Handling.
- How Vite splits the code
When Vite (in fact Rollup, the bundler it uses for builds) finds a dynamic import(), it does something very useful: it places the imported module and its exclusive dependencies in a separate JavaScript file, called a chunk. This is code splitting.
In development (npm run dev), Vite serves each module separately. Open the browser's developer tools, go to the Network tab, filter by "JS" and reload the page: you will not see any request for BuildingMap.vue. Click the catalogue's "Map" tab and it will appear at that moment.
In production (npm run build), the output will show the separate chunk:
dist/index.html 0.46 kB │ gzip: 0.30 kB
dist/assets/index-D4f8a2Lk.css 6.12 kB │ gzip: 1.85 kB
dist/assets/BuildingMap-Bq7xT0cW.js 2.31 kB │ gzip: 1.10 kB
dist/assets/index-C9kLm3Pa.js 78.40 kB │ gzip: 30.95 kB(The names include a hash and the exact sizes will vary.) The main file (index-...js) no longer contains the map; BuildingMap-...js is only downloaded if the user opens that view. You can check this with npm run preview, which serves the built version.
This same mechanism is the one used to load whole routes on demand, which you will see in Setting Up Vue Router, and its effect on performance is analysed in Performance Optimization. Do not make every component async: each chunk is an extra request. Reserve it for pieces that are large and not essential at the start: secondary views, editors, charts, maps, complex modals.
- Case study: the catalogue's view switcher
Colmena will display its catalogue in three ways:
- Grid: the cards we already have.
- Table: one row per room, sortable by column, compact for comparing.
- Map: the building floor by floor, with each room drawn in its position. In a real project it would load a detailed SVG or a zoom library, so we will treat it as a heavy, async component.
All three will share an interface: the rooms and selectedId props, and the select and book events. As the catalogue grows, we will group its components in a src/components/catalog/ subfolder, just as we anticipated in 03-01. (Do not confuse them with the page views, HomeView, RoomsView..., which will arrive with the router in module 4 in the src/views/ folder.)
11.1 GridView.vue
The grid is what App.vue currently renders with RoomList and its slot. We move it into its own component, src/components/catalog/GridView.vue:
<script setup>
import RoomList from '../RoomList.vue'
import RoomCard from '../RoomCard.vue'
const { rooms, selectedId = null } = defineProps({
rooms: { type: Array, required: true },
selectedId: String
})
const emit = defineEmits(['select', 'book'])
</script>
<template>
<RoomList :rooms>
<template #room="{ room }">
<RoomCard
:room
:selected="room.id === selectedId"
@select="emit('select', $event)"
@book="emit('book', $event)"
>
<template v-if="!room.available" #actions>
<p class="notice">Under maintenance: not accepting bookings.</p>
</template>
</RoomCard>
</template>
</RoomList>
</template>
<style scoped>
.notice {
color: #b00020;
font-weight: bold;
}
</style>It is the same markup as in Slots, but now the slot's content belongs to GridView: that is why it uses its selectedId prop and re-emits the events, and that is why it needs its own .notice style.
11.2 TableView.vue
Create src/components/catalog/TableView.vue:
<script setup>
import { ref, computed, onActivated, useTemplateRef } from 'vue'
import BaseButton from '../base/BaseButton.vue'
import StatusBadge from '../StatusBadge.vue'
const { rooms, selectedId = null } = defineProps({
rooms: { type: Array, required: true },
selectedId: String
})
const emit = defineEmits(['select', 'book'])
// --- The table's own sorting (local state that KeepAlive will preserve) ---
const columns = [
{ key: 'name', label: 'Room' },
{ key: 'floor', label: 'Floor' },
{ key: 'capacity', label: 'Capacity' },
{ key: 'hourlyPrice', label: 'Price/h' }
]
const sortColumn = ref('name')
const ascending = ref(true)
const sortedRooms = computed(() => {
const factor = ascending.value ? 1 : -1
const key = sortColumn.value
return rooms.toSorted((a, b) =>
typeof a[key] === 'string'
? a[key].localeCompare(b[key], 'en') * factor
: (a[key] - b[key]) * factor
)
})
function sortBy(key) {
if (sortColumn.value === key) {
ascending.value = !ascending.value // same column: reverse the direction
} else {
sortColumn.value = key
ascending.value = true
}
}
function sortDirection(key) {
if (sortColumn.value !== key) return 'none'
return ascending.value ? 'ascending' : 'descending'
}
// --- Scroll position: saved when scrolling and restored when coming back ---
const container = useTemplateRef('table-container')
let scrollPosition = 0
function rememberScroll() {
scrollPosition = container.value.scrollTop
}
onActivated(() => {
container.value.scrollTop = scrollPosition
})
</script>
<template>
<div ref="table-container" class="table-container" @scroll="rememberScroll">
<table class="room-table">
<thead>
<tr>
<th v-for="column in columns" :key="column.key" :aria-sort="sortDirection(column.key)">
<button type="button" class="room-table__sort" @click="sortBy(column.key)">
{{ column.label }}
<span aria-hidden="true">
{{ sortColumn === column.key ? (ascending ? '▲' : '▼') : '' }}
</span>
</button>
</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr
v-for="room in sortedRooms"
:key="room.id"
:class="{ 'room-table__row--selected': room.id === selectedId }"
>
<td>{{ room.name }}</td>
<td>{{ room.floor }}</td>
<td>{{ room.capacity }}</td>
<td>€{{ room.hourlyPrice }}</td>
<td><StatusBadge :status="room.available ? 'available' : 'unavailable'" /></td>
<td class="room-table__actions">
<BaseButton
variant="secondary"
:disabled="room.id === selectedId"
@click="emit('select', room.id)"
>
Select
</BaseButton>
<BaseButton
:disabled="!room.available"
@click="emit('book', { roomId: room.id, attendees: 1 })"
>
Book
</BaseButton>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<style scoped>
.table-container {
max-height: 220px; /* with several rooms, a scroll bar appears */
overflow-y: auto;
border-radius: 10px;
background: white;
}
.room-table {
width: 100%;
border-collapse: collapse;
}
.room-table th,
.room-table td {
padding: 0.5rem 0.75rem;
border-bottom: 1px solid #eeeeee;
text-align: left;
}
.room-table thead th {
position: sticky; /* the header stays fixed when scrolling */
top: 0;
background: var(--color-background);
}
.room-table__sort {
border: none;
background: none;
font: inherit;
font-weight: bold;
cursor: pointer;
}
.room-table__row--selected {
background: #fff4e5;
}
.room-table__actions {
display: flex;
gap: 0.4rem;
}
</style>- Sorting by column is the table's local state (
sortColumn,ascending), independent ofRoomFilters' price sorting. It is exactly the kind of state that is lost when switching tabs withoutKeepAlive. aria-sorton each<th>tells screen readers which column the table is sorted by and in which direction; the buttons inside the headers make the sorting accessible from the keyboard.- The scroll position is saved in an ordinary variable (it does not need to be reactive: it is not rendered) every time the user scrolls the container, and it is restored in
onActivated. SinceonActivatedalso runs on the first mount, the first time it restores a harmless 0. - The price is shown as
€{{ room.hourlyPrice }}so as not to create a fourth copy offormatPrice; the plugin in module 7 will tidy this up.
11.3 BuildingMap.vue, the heavy component
Create src/components/catalog/BuildingMap.vue:
<script setup>
import { ref, computed, onActivated, onDeactivated } from 'vue'
import BaseButton from '../base/BaseButton.vue'
const { rooms, selectedId = null } = defineProps({
rooms: { type: Array, required: true },
selectedId: String
})
const emit = defineEmits(['select', 'book'])
// Position of each room on its floor's plan (a 400 × 240 canvas)
const layout = {
panal: { x: 20, y: 20, width: 200, height: 130 },
polen: { x: 240, y: 20, width: 140, height: 90 },
nectar: { x: 20, y: 20, width: 250, height: 150 },
celda: { x: 300, y: 20, width: 80, height: 70 },
enjambre: { x: 20, y: 20, width: 360, height: 200 }
}
// Local state: which floor is being viewed
const visibleFloor = ref(1)
const floorRooms = computed(() =>
rooms.filter((room) => room.floor === visibleFloor.value && layout[room.id])
)
const selectedRoomOnFloor = computed(() =>
floorRooms.value.find((room) => room.id === selectedId)
)
onActivated(() => console.log(`[BuildingMap] activated on floor ${visibleFloor.value}`))
onDeactivated(() => console.log('[BuildingMap] deactivated: still in the cache'))
</script>
<template>
<div class="map">
<div class="map__floors" role="group" aria-label="Building floor">
<BaseButton
v-for="floor in 3"
:key="floor"
variant="secondary"
:aria-pressed="visibleFloor === floor"
@click="visibleFloor = floor"
>
Floor {{ floor }}
</BaseButton>
</div>
<svg viewBox="0 0 400 240" class="map__canvas" role="group" :aria-label="`Floor ${visibleFloor} plan`">
<rect x="0" y="0" width="400" height="240" class="map__ground" />
<g
v-for="room in floorRooms"
:key="room.id"
class="map__room"
:class="{
'map__room--selected': room.id === selectedId,
'map__room--unavailable': !room.available
}"
role="button"
tabindex="0"
:aria-label="`${room.name}, ${room.capacity} people`"
@click="emit('select', room.id)"
@keydown.enter="emit('select', room.id)"
>
<rect
:x="layout[room.id].x"
:y="layout[room.id].y"
:width="layout[room.id].width"
:height="layout[room.id].height"
rx="8"
/>
<text :x="layout[room.id].x + 10" :y="layout[room.id].y + 24">
{{ room.name }}
</text>
</g>
</svg>
<p v-if="floorRooms.length === 0">No room on this floor matches the filters.</p>
<BaseButton
v-if="selectedRoomOnFloor?.available"
@click="emit('book', { roomId: selectedRoomOnFloor.id, attendees: 1 })"
>
Book the {{ selectedRoomOnFloor.name }}
</BaseButton>
</div>
</template>
<style scoped>
.map__floors {
display: flex;
gap: 0.5rem;
margin-bottom: 0.75rem;
}
.map__canvas {
width: 100%;
max-width: 600px;
border-radius: 10px;
background: white;
}
.map__ground {
fill: var(--color-background);
}
.map__room {
cursor: pointer;
}
.map__room rect {
fill: #ffe8b3;
stroke: var(--color-honey-dark);
stroke-width: 2;
}
.map__room--selected rect {
fill: var(--color-honey);
stroke-width: 4;
}
.map__room--unavailable rect {
fill: #eeeeee;
stroke: #9e9e9e;
}
.map__room:focus-visible rect {
stroke: var(--color-text);
stroke-width: 4;
}
</style>- The SVG is generated with
v-forover the rooms on the visible floor, with bound attributes (:x,:width...) like any other element. Rooms excluded by the filters do not appear. - Each room is accessible:
role="button",tabindex="0"so that it can be reached with the Tab key, and@keydown.enterto activate it from the keyboard. visibleFlooris local state thatKeepAlivewill preserve: if the user is looking at floor 3, on coming back to the map it will still be on floor 3.- The
onActivatedandonDeactivatedmessages will let you see in the console when the component goes into and comes out of the cache.
11.4 Loading and error indicators
Create two small components in the same folder. They must be static: if they were async as well, there would be nothing to show while they were downloading.
<!-- src/components/catalog/MapLoading.vue -->
<template>
<p class="map-state" role="status">Loading the building map…</p>
</template><!-- src/components/catalog/MapError.vue -->
<script setup>
const { error } = defineProps({ error: Error })
</script>
<template>
<div class="map-state" role="alert">
<p>The building map could not be loaded.</p>
<p><small>{{ error?.message }}</small></p>
<p>Check your connection and reload the page.</p>
</div>
</template>11.5 App.vue: a view switcher with KeepAlive
In the script of App.vue:
import { defineAsyncComponent } from 'vue' // add it to the existing 'vue' import
import GridView from './components/catalog/GridView.vue'
import TableView from './components/catalog/TableView.vue'
import MapLoading from './components/catalog/MapLoading.vue'
import MapError from './components/catalog/MapError.vue'
// RoomList and RoomCard are no longer imported here: GridView uses them
// The map is only downloaded when the user opens that view
const BuildingMap = defineAsyncComponent({
loader: () => import('./components/catalog/BuildingMap.vue'),
loadingComponent: MapLoading,
delay: 200,
errorComponent: MapError,
timeout: 10000
})
// --- Catalogue view ---
const views = {
grid: { component: GridView, label: 'Grid' },
table: { component: TableView, label: 'Table' },
map: { component: BuildingMap, label: 'Map' }
}
const currentView = ref('grid')
const hasResults = computed(
() => !loading.value && !error.value && visibleRooms.value.length > 0
)In the catalogue's template, the <template v-else> branch keeps the free rooms paragraph and gains the view switcher; the view itself is placed after the chain of states, wrapped in KeepAlive:
<!-- ... loading / error / empty / no results branches, no changes ... -->
<template v-else>
<p>
<strong>{{ freeRooms }}</strong> free rooms out of {{ catalog.length }} ·
showing {{ visibleRooms.length }}
</p>
<div class="view-switcher" role="tablist" aria-label="Catalogue view">
<BaseButton
v-for="(view, key) in views"
:key="key"
variant="secondary"
role="tab"
:aria-selected="currentView === key"
@click="currentView = key"
>
{{ view.label }}
</BaseButton>
</div>
</template>
<!-- Outside the v-if chain: KeepAlive is not unmounted when the catalogue reloads -->
<KeepAlive :max="3">
<component
:is="views[currentView].component"
v-if="hasResults"
:rooms="visibleRooms"
:selected-id="selectedRoomId"
@select="selectRoom"
@book="prepareBooking"
/>
</KeepAlive>/* In the <style scoped> of App.vue */
.view-switcher {
display: flex;
gap: 0.5rem;
margin-bottom: 1rem;
}Notice the decisions:
viewsmaps each key to its component and its label. The object is not reactive; the state is onlycurrentView.BuildingMap, even though it is async, is used in exactly the same way as the other two.- The switcher's buttons are generated with
v-forover an object ((view, key)) and use the tab roles (role="tablist",role="tab",aria-selected), which reachBaseButton's<button>as fallthrough attributes. KeepAliveis outside thev-ifchain, and thehasResultscondition goes inside, on the<component>. That way, when you change floor and the catalogue goes through "Loading rooms…", the active view is deactivated instead of being destroyed, and the cache survives. IfKeepAlivewere inside<template v-else>, every reload would unmount it and you would lose the state of all three views.:max="3"allows all three views to be stored at once.
11.6 Try it
- State preserved. In the grid, add 2 attendees to the Polen Room. Switch to "Table", sort it by price in descending order and scroll it to the bottom. Switch to "Map" and choose floor 2. Go back to each view: the table is still sorted and scrolled, the map is on floor 2 and Polen has its 2 attendees.
- Without
KeepAlive. Temporarily remove the<KeepAlive>tags and repeat: each view returns to its initial state and, when you go back to the grid, you will see the[RoomCard] ... readymessages in the console again. Put the tags back. - Activation cycle. With the console open, switch between "Map" and another view: you will see
BuildingMap's activation and deactivation messages, but never mounting or unmounting ones. Change floor in the filters with the map active: it is deactivated during the load and reactivated when it finishes. - Loading on demand. In the browser's Network tab, filter by "BuildingMap" and reload the page: there are no requests. Click "Map": the request appears at that moment. Click it again later: it is not repeated.
- Loading indicator. To see it, simulate a slow network: in the Network tab, choose the Slow 3G profile, reload and click "Map"; after 200 ms, "Loading the building map…" will appear. To see the error, choose Offline before clicking "Map" for the first time.
- Build. Run
npm run buildand look for theBuildingMap-[hash].jsfile in the output.
Common Mistakes and Tips
- Passing the component's name as a string to
:isin<script setup>. It will not be resolved: pass the imported object. Strings only work for HTML elements or components registered by name. - Storing components in a
reforreactive. Vue will make them reactive and warn you. Store the key, or useshallowRef/markRaw. - Putting
KeepAliveinside av-if. It is destroyed along with its cache. Put the condition on the component inside. - Using
onMountedto refresh a cached component. It only runs the first time; useonActivated. - Forgetting to pause timers in
onDeactivated. A cached component is still alive. - Making a
loadingComponentasync. There would be nothing to show while it loaded; they must be static. - Splitting too much. Each async component is one more request. Reserve it for pieces that are large and not needed at start-up.
- Tip: when several components are interchangeable with
<component :is>, document their common interface (props and events) and respect it in all of them. That way, adding a new view means creating a file and adding a line to theviewsobject.
Exercises
Exercise 1. Add a fourth view, "List" (ListView.vue), which shows each room on one line with its name, its capacity and a "Select" button. It must have the same interface as the others. How many places in App.vue do you have to touch? What happens with KeepAlive's :max="3"?
Exercise 2. Make KeepAlive preserve only the table and the map, but not the grid. Check what happens to the cards' attendee counters when you go back and forth. Why might it make sense in a real application not to cache a view?
Exercise 3. In BuildingMap, add a small "Updated N s ago" indicator that counts the seconds elapsed since the last time the map was shown, using a setInterval. The timer must not keep running while the map is in the cache or after it has been unmounted.
Solutions
Solution 1.
<!-- src/components/catalog/ListView.vue -->
<script setup>
import BaseButton from '../base/BaseButton.vue'
const { rooms, selectedId = null } = defineProps({
rooms: { type: Array, required: true },
selectedId: String
})
const emit = defineEmits(['select', 'book'])
</script>
<template>
<ul class="list-view">
<li v-for="room in rooms" :key="room.id">
<strong>{{ room.name }}</strong> · {{ room.capacity }} people
<BaseButton
variant="secondary"
:disabled="room.id === selectedId"
@click="emit('select', room.id)"
>
Select
</BaseButton>
</li>
</ul>
</template>// App.vue: the import and an entry in views
import ListView from './components/catalog/ListView.vue'
const views = {
grid: { component: GridView, label: 'Grid' },
table: { component: TableView, label: 'Table' },
list: { component: ListView, label: 'List' },
map: { component: BuildingMap, label: 'Map' }
}Only two places in the script: the import and the views object. The template does not change, because the switcher is generated with v-for and <component :is> accepts any view that respects the interface. Although ListView does not emit book, declaring it keeps the common interface. With :max="3", when you visit all four views, the least recently used one is evicted from the cache and loses its state; raise it to 4 if you want to keep them all.
Solution 2.
When you go back to the grid, it is mounted from scratch: the cards go back to 0 attendees and the console shows the mounting messages again. BuildingMap works in include even though it is async: KeepAlive uses the name of the component once it has loaded. Not caching a view makes sense when its data must always be fresh when it is shown (for example, real-time availability), when its state adds nothing for the user or when it is very heavy in memory (thousands of elements in the DOM).
Solution 3.
// BuildingMap.vue
import { ref, computed, onActivated, onDeactivated } from 'vue'
const seconds = ref(0)
let interval = null
onActivated(() => {
seconds.value = 0
interval = setInterval(() => seconds.value++, 1000)
})
onDeactivated(() => {
clearInterval(interval)
interval = null
})There is no need for onMounted or onUnmounted: onActivated also runs on the first mount and onDeactivated also runs on the final unmount, so the pair covers every case. If the component were used without KeepAlive, it would still work for that very reason.
Conclusion
<component :is> renders whichever component an expression specifies: in <script setup>, the imported object (stored in a non-reactive structure, with the state reduced to a key), or the name of an HTML element as a string. When the component changes, the previous one is destroyed, unless <KeepAlive> keeps it in a cache, controlled with include, exclude and max, and with the onActivated and onDeactivated hooks to react to entering and leaving the cache; the cache lives as long as KeepAlive is mounted, so the conditions go inside it. defineAsyncComponent turns a dynamic import into a component that is downloaded the first time it is rendered, with loading and error components, delay, timeout and retries, and Vite places that component in a separate chunk of code. Colmena now has a catalogue with three interchangeable views (GridView, TableView and an async BuildingMap), each with its state preserved by KeepAlive.
In this lesson we have reviewed almost every way in which components communicate: props, events, v-model, slots, exposed refs... and the views' common interface has made it obvious that App.vue is the point where everything is coordinated. One question remains: what about data needed by components that are far apart in the tree, such as the signed-in member, which matters to both the header and the form? In Component Communication we will arrange all the channels on a map, study provide/inject and see why, beyond a certain point, something more is needed.
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
