Until now, each of Colmena's routes corresponded to a fixed address: /, /rooms, /book. But many screens show one specific item from a collection: the Néctar Room's spec sheet, the Polen Room's, the Celda Booth's... It would make no sense to write one route per room, and besides, the catalogue may grow. The solution is dynamic segments: parts of the route that act as variables, so that /rooms/nectar and /rooms/polen use the same route and the same view with a different param. In this lesson you will learn to declare them, to read them with useRoute(), to receive them as props so that the view does not depend on the router, to react when the param changes without the view changing, to use optional and repeatable params and params with regular expressions, and to show a 404 page when the item does not exist. In Colmena you will create each room's spec sheet at /rooms/:id and put the form's room in the URL: /book/:roomId.
Contents
- Dynamic segments
- Reading params with
useRoute() - Receiving params as props
- When only the param changes: the component is reused
- Optional and repeatable params and params with a regular expression
- Table of patterns
- When the item does not exist: a 404 that keeps the URL
- Case study: each room's spec sheet and the room in the form's URL
- Dynamic segments
A dynamic segment is written with a colon in front of its name:
| URL visited | Does it match? | Params |
|---|---|---|
/rooms/nectar |
Yes | { id: 'nectar' } |
/rooms/enjambre |
Yes | { id: 'enjambre' } |
/rooms |
No: the segment is missing | — |
/rooms/nectar/photos |
No: there is one segment too many | — |
- A param covers one segment: the text between two slashes. That is why
/rooms/nectar/photosdoes not match. - Its value is always a string. In
/invoices/141, the param would be'141', not141. - There can be several in one route:
/floors/:floor/rooms/:idproduces{ floor: '2', id: 'nectar' }.
To link to a route with params, the most convenient way is to do it by name and pass the params in an object:
<RouterLink :to="{ name: 'room-detail', params: { id: 'nectar' } }">Néctar Room</RouterLink>
<!-- generates <a href="/rooms/nectar"> -->The router builds the URL and encodes special characters (a space becomes %20, an é becomes %C3%A9), something you could easily forget when writing `/rooms/${id}` by hand. If a required param is missing, Vue Router throws a clear error (Missing required param "id") instead of generating a broken link.
- Reading params with
useRoute()
useRoute()Inside a component, the useRoute() composable returns the current route, a reactive object with all the information in the URL:
<script setup>
import { computed } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
const roomId = computed(() => route.params.id)
</script>
<template>
<p>You are viewing the room "{{ route.params.id }}"</p>
</template>| Property | Example for /rooms/nectar?view=photos#floor |
What it contains |
|---|---|---|
route.path |
'/rooms/nectar' |
The path, without the query or the anchor |
route.fullPath |
'/rooms/nectar?view=photos#floor' |
The complete address |
route.params |
{ id: 'nectar' } |
The route params |
route.query |
{ view: 'photos' } |
The query parameters (04-05) |
route.hash |
'#floor' |
The anchor |
route.name |
'room-detail' |
The name of the matching route |
route.matched |
[ { path: '/rooms/:id', ... } ] |
The matching route records (04-04) |
route.meta |
{} |
The route's metadata (04-06) |
Three important rules:
useRoute()is called at the top level of<script setup>, likeinject(in fact, under the hood it usesinject).- The
routeobject is reactive, but its properties are replaced on every navigation. If you writeconst id = route.params.idorconst { params } = route, you store the value at that moment and it will not be updated. Always read throughroute(route.params.id) in the template, in acomputedor in awatchgetter. - In the template you have
$routewithout needing to calluseRoute(), and in the Options API,this.$route. It is the same object.
- Receiving params as props
Reading route.params works, but it ties the component to the router: it can only be used as the screen of a route that has that param. If you wanted to show a room's spec sheet inside a modal, or to test the component in isolation (module 8), you would have to simulate a route. The alternative is for the router to deliver the params as props, with the route's props option:
<!-- RoomDetailView.vue: knows nothing about the router -->
<script setup>
const { id } = defineProps({ id: { type: String, required: true } })
</script>The props option accepts three forms:
| Form | Example | What the component receives | Use it when... |
|---|---|---|---|
| Boolean | props: true |
Each route param (route.params) as a prop of the same name |
The params can be used as they are (strings) |
| Object | props: { mode: 'compact' } |
Those fixed props, always the same | The same view is used in several routes with different configurations |
| Function | props: (route) => ({ number: Number(route.params.number) }) |
Whatever the function returns; it receives the route | You need to convert types, combine params with the query or rename |
An example of each of the last two:
// Object: the same view in two routes, with a different configuration
{ path: '/rooms', component: RoomsView, props: { initialView: 'grid' } },
{ path: '/map', component: RoomsView, props: { initialView: 'map' } },
// Function: convert the param (a string) into a number
{
path: '/invoices/:number',
component: InvoiceView,
props: (route) => ({ number: Number(route.params.number) })
}The function runs every time the route changes, so the props are kept up to date. It must be a stateless function (do not store anything between calls).
Course rule: in Colmena, views will receive their params as props. We will reserve
useRoute()for whatever is not the view's data but data about the navigation itself (the full address, the query in 04-05, the breadcrumbs in 04-04).
- When only the param changes: the component is reused
Imagine you are on /rooms/nectar and you click a link to /rooms/polen. Both URLs correspond to the same route (room-detail) and to the same view. Vue Router does not unmount the view and mount it again: it reuses it, and only its props (or route.params) change. This is more efficient, but it has a consequence: setup does not run again, and neither does onMounted. A view that loads its data like this:
// ✗ Only loads the first room visited
const { id } = defineProps({ id: String })
const room = ref(null)
onMounted(async () => {
room.value = await fetchRoom(id)
})will show the Néctar Room even though the URL already says /rooms/polen. There are three ways of solving this:
4.1 Watching the param
The most common one: a watch on the prop (or on route.params.id) with immediate: true, which serves both for the first load and for the changes:
const { id } = defineProps({ id: String })
watch(
() => id, // getter: the destructured prop is read through a function (03-02)
async (roomId) => {
room.value = await fetchRoom(roomId)
},
{ immediate: true }
)It is the same pattern we already used to reload the catalogue when floorFilter changed (02-05), and it allows the same things: cancelling the previous request with AbortController and onWatcherCleanup if the user switches room before the response arrives.
4.2 onBeforeRouteUpdate
Vue Router offers an in-component guard that runs when the route changes but the component is reused:
import { onBeforeRouteUpdate } from 'vue-router'
onBeforeRouteUpdate(async (to, from) => {
if (to.params.id !== from.params.id) {
room.value = await fetchRoom(to.params.id)
}
})- It receives
to(the destination route) andfrom(the origin route). You have to read the param fromto: when it runs, the navigation has not yet been completed and the props still have the old value. - It does not run on the first load, so you will also need an
onMounted(or similar) for that. - Since it is a guard, the navigation waits for the function to finish: the URL does not change until the new room has arrived. And it can cancel the navigation (by returning
false), something we will study in 04-06.
4.3 Forcing a remount with key
The third option is to force Vue to treat each URL as a different component, by putting a key on the <RouterView>:
When the key changes, Vue unmounts the view and mounts it again, as you learnt with v-for in 02-08. It is the quickest "fix", but the most expensive one: all the local state is destroyed and the whole tree is recreated on every navigation, even when only the query changes.
| Technique | First load | Param change | Does it delay the navigation? | Recommendation |
|---|---|---|---|---|
watch with immediate |
Yes | Yes | No: the URL changes straight away and the view shows "loading" | The default option |
onBeforeRouteUpdate |
No (add onMounted) |
Yes | Yes: it waits for the data | When you prefer not to change screen until you have the data, or you need to cancel |
<RouterView :key> |
Yes | Yes, remounting everything | No | Only as a last resort |
- Optional and repeatable params and params with a regular expression
5.1 Optional: ?
A ? after the param makes it optional:
{ path: '/bookings/:date?', component: ScheduleView }
// /bookings → date has no value: today's schedule is shown
// /bookings/2026-11-03 → date: '2026-11-03'5.2 Repeatable: + and *
A + allows one or more segments and a *, zero or more. The param's value becomes an array:
{ path: '/map/:floors+', component: MapView }
// /map/1 → floors: ['1']
// /map/1/3 → floors: ['1', '3']
// /map → does not match (at least one is needed)
{ path: '/map/:floors*', component: MapView }
// /map → also matches, with no floorsWhen linking, you also pass an array: { name: 'map', params: { floors: ['1', '3'] } }.
5.3 With a regular expression: :param(regex)
By default, a param accepts any text without slashes. In brackets you can restrict what it accepts with a regular expression:
{ path: '/invoices/:number(\\d+)', component: InvoiceView }
// /invoices/141 → number: '141'
// /invoices/f-141 → does not match (and will end up on the 404 page)- The backslash is written twice (
\\d) because thepathis a JavaScript string:'\\d'produces the text\d. - Even though the expression only allows digits, the value is still a string. To convert it, use
propsin function mode. - It is also useful for stopping two routes with the same shape from treading on each other:
/:roomId([a-z-]+)and/:bookingId(\\d+)can coexist, because each URL fits only one of them.
They can be combined: /:chapters(\\d+)+ accepts one or more numeric segments. And the 404 catch-all route, /:pathMatch(.*)*, is nothing more than a repeatable param with the expression "anything, slashes included".
- Table of patterns
| Pattern | Matches | Does not match | params |
|---|---|---|---|
/rooms/:id |
/rooms/nectar |
/rooms, /rooms/a/b |
{ id: 'nectar' } |
/floors/:floor/rooms/:id |
/floors/2/rooms/nectar |
/floors/2 |
{ floor: '2', id: 'nectar' } |
/bookings/:date? |
/bookings, /bookings/2026-11-03 |
/bookings/a/b |
{ date: '2026-11-03' } or no value |
/map/:floors+ |
/map/1, /map/1/3 |
/map |
{ floors: ['1', '3'] } |
/map/:floors* |
/map, /map/1/3 |
— | { floors: ['1', '3'] } or no value |
/invoices/:number(\\d+) |
/invoices/141 |
/invoices/f-141 |
{ number: '141' } (a string) |
/rooms/:id([a-z-]+) |
/rooms/nectar |
/rooms/Nectar1 |
{ id: 'nectar' } |
/:pathMatch(.*)* |
Any route | — | { pathMatch: ['does', 'not-exist'] } |
By default, routes are not case-sensitive (/ROOMS/nectar matches /rooms/:id) and they accept an optional trailing slash (/rooms/). The sensitive: true and strict: true options, on the route or in createRouter, change that behaviour. If you are unsure what matches what, the routes tab in Vue DevTools and router.resolve('/rooms/nectar') in the console will tell you.
- When the item does not exist: a 404 that keeps the URL
The /rooms/:id route matches /rooms/basement even though no room exists with that id: the router only checks the shape of the URL, not whether the data exists. The one who knows is the view, when it requests the room from the API and the API responds that it does not exist.
What should the user see? A 404 page, but without changing the URL: if we redirect them to another address (for example, /not-found), they lose the reference to what they typed, and the Back button takes them back to the broken URL, which redirects them again... The simplest technique is for the detail view to render the 404 component instead of the spec sheet:
<template>
<NotFoundView v-if="notFound" />
<section v-else>
<!-- the room's spec sheet -->
</section>
</template>A view is a component like any other: it can be imported and used in a template. To distinguish "does not exist" from "the connection has failed" (which deserves a Retry button, not a 404), the API must return distinguishable errors, as a real server does with its HTTP status codes. There is another technique, which consists of deciding this before entering the view and showing the 404 route while keeping the URL; we will see it in Navigation Guards.
- Case study: each room's spec sheet and the room in the form's URL
8.1 The API distinguishes "does not exist"
In src/api/rooms.js, change fetchRoom's error to mark it with a status code, as a server would:
// src/api/rooms.js, inside fetchRoom
if (!room) {
const error = new Error(`No room exists with the id "${id}"`)
error.status = 404 // the HTTP status code that a real server would return
throw error
}8.2 The routes
In src/router/index.js, add the room spec sheet and change the form's route:
{
path: '/rooms/:id([a-z-]+)',
name: 'room-detail',
component: () => import('@/views/RoomDetailView.vue'),
props: true
},
{
path: '/book/:roomId([a-z-]+)', // before: '/book'
name: 'book',
component: () => import('@/views/BookingView.vue'),
props: true
},([a-z-]+): room ids are lower case, without accents and with, at most, hyphens (panal,nectar...). A URL such as/rooms/123does not even reach the view: it goes straight to the router's 404.props: true: the views will receiveidandroomIdas props.- By changing
/bookto/book/:roomId, any link to{ name: 'book' }withoutparamswill throw an error. There is only one, the one inRoomsView; we fix it in section 8.5.
8.3 RoomDetailView.vue
Create src/views/RoomDetailView.vue:
<script setup>
import { ref, computed, watch, onWatcherCleanup } from 'vue'
import StatusBadge from '@/components/StatusBadge.vue'
import BaseButton from '@/components/base/BaseButton.vue'
import BasePanel from '@/components/base/BasePanel.vue'
import NotFoundView from './NotFoundView.vue'
import { rooms } from '@/data/rooms.js'
import { fetchRoom } from '@/api/rooms.js'
const { id } = defineProps({
id: { type: String, required: true }
})
const room = ref(null)
const loading = ref(false)
const error = ref('')
const notFound = ref(false)
async function loadRoom(roomId, signal) {
loading.value = true
error.value = ''
notFound.value = false
try {
room.value = await fetchRoom(roomId, { signal })
} catch (e) {
if (e.name === 'AbortError') return // a more recent request has replaced it
room.value = null
if (e.status === 404) {
notFound.value = true
} else {
error.value = e.message
}
}
loading.value = false
}
// First load and every change of room (the view is reused between /rooms/a and /rooms/b)
watch(
() => id,
(roomId) => {
const controller = new AbortController()
onWatcherCleanup(() => controller.abort())
loadRoom(roomId, controller.signal)
},
{ immediate: true }
)
// For navigating to the other rooms without going back to the catalogue
const otherRooms = computed(() => rooms.filter((r) => r.id !== id))
// formatPrice: yet another copy, until the plugin in module 7
const euroFormatter = new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'EUR' })
function formatPrice(amount) {
return euroFormatter.format(amount)
}
</script>
<template>
<NotFoundView v-if="notFound" />
<section v-else class="detail">
<p><RouterLink :to="{ name: 'rooms' }">← Catalogue</RouterLink></p>
<p v-if="loading">Loading the room…</p>
<div v-else-if="error" class="notice" role="alert">
<p>{{ error }}</p>
<BaseButton @click="loadRoom(id)">
<template #icon>↻</template>
Retry
</BaseButton>
</div>
<BasePanel v-else-if="room">
<template #header>
<h2>{{ room.name }}</h2>
<StatusBadge :status="room.available ? 'available' : 'unavailable'" />
</template>
<img
:src="`/img/rooms/${room.id}.webp`"
:alt="`Photo of the ${room.name}`"
class="detail__photo"
/>
<dl class="spec-sheet">
<dt>Floor</dt>
<dd>{{ room.floor }}</dd>
<dt>Capacity</dt>
<dd>{{ room.capacity }} people</dd>
<dt>Price per hour</dt>
<dd>{{ formatPrice(room.hourlyPrice) }}</dd>
<dt>Equipment</dt>
<dd>{{ room.equipment.join(', ') }}</dd>
</dl>
<template #footer>
<RouterLink
v-if="room.available"
:to="{ name: 'book', params: { roomId: room.id } }"
class="detail__book"
>
Book this room
</RouterLink>
<p v-else class="notice">Under maintenance: not accepting bookings.</p>
</template>
</BasePanel>
<nav class="detail__others" aria-label="Other rooms">
<h3>Other rooms</h3>
<ul>
<li v-for="other in otherRooms" :key="other.id">
<RouterLink :to="{ name: 'room-detail', params: { id: other.id } }">
{{ other.name }}
</RouterLink>
</li>
</ul>
</nav>
</section>
</template>
<style scoped>
.detail__photo {
width: 100%;
max-height: 240px;
object-fit: cover;
border-radius: 8px;
}
.detail__book {
padding: 0.5rem 1rem;
border-radius: 8px;
background: var(--color-honey);
color: var(--color-text);
font-weight: bold;
text-decoration: none;
}
.detail__others ul {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
padding: 0;
list-style: none;
}
.notice {
color: #b00020;
}
</style>Let's review the decisions:
idarrives as a prop (thanks toprops: true): the view does not import anything fromvue-router. It could be shown in a modal by passing itid="nectar".- The
watchwithimmediateloads the room when the view is mounted and every timeidchanges, cancelling the previous request. It is the pattern from section 4.1, with the cancellation from 02-05. - Four states (loading, an error with Retry, does not exist, and data), in line with the pattern from 02-07. The connection error and the non-existent room are handled differently thanks to
e.status === 404. <NotFoundView v-if="notFound" />: the 404 is rendered in place, and the URL/rooms/basementis kept.- The Retry button calls
loadRoom(id)without a signal: it is a one-off request that does not compete with any others. - "Book this room" is a link with params to the
bookroute. For a room under maintenance, the link is not shown (a link cannot be "disabled"); an explanation is shown instead. - "Other rooms" uses the local data (
rooms) for the names, asBookingFormalready did. When one is clicked, the route changes but the view is reused: thewatchis what makes the new room load.
8.4 Links from RoomCard
To reach the spec sheet from the catalogue, make the room's name on the card a link. In the template of RoomCard.vue, inside the heading that shows the name:
<!-- RoomCard.vue: the room's name becomes a link to its spec sheet -->
<RouterLink :to="{ name: 'room-detail', params: { id: room.id } }" class="card__link">
{{ room.name }}
</RouterLink>Is it right for a reusable component to know about a route? It is a reasonable concession: a room's spec sheet is the way to view a room throughout the application, and linking is not the same as deciding where to navigate. The consequence is that, to render RoomCard outside the application (in a test), you will need a router or a stand-in for RouterLink, something we will solve in Mocking Dependencies. If you prefer to avoid this, the alternative is for the view to decide through the #actions slot (exercise 1).
8.5 The form's room, in the URL
With /book/:roomId, the room to be booked no longer needs to travel through memory: the URL is the state. That allows us to remove the temporary proposal from the previous lesson.
In App.vue, delete proposal and proposeBooking, and remove them from the provide:
In RoomsView.vue, remove the inject of BOOKINGS_KEY, proposedRoomName and the import of the key, and simplify prepareBooking:
// RoomsView.vue
const bookingReady = ref(false)
function prepareBooking({ roomId }) {
selectRoom(roomId)
bookingReady.value = true
}<!-- RoomsView.vue: the notice links to the room in the URL -->
<p v-if="bookingReady" class="note" role="status">
Booking ready: {{ selectedRoom.name }} ·
<RouterLink :to="{ name: 'book', params: { roomId: selectedRoomId } }">
Complete the booking →
</RouterLink>
</p>In BookingView.vue, the room arrives as a prop:
// BookingView.vue: replaces the inject line
const { roomId } = defineProps({
roomId: { type: String, required: true }
})
const { bookings, recordBooking } = inject(BOOKINGS_KEY)<!-- BookingView.vue -->
<p><RouterLink :to="{ name: 'room-detail', params: { id: roomId } }">← Back to the room's spec sheet</RouterLink></p>
<BookingForm ref="booking-form" :room-id="roomId" @create="createBooking" />BookingFormdoes not change: it still receivesroomIdas a prop. If the user goes from/book/panalto/book/polen,BookingViewis reused, its prop changes, and thewatchthat the form has had since 03-03 updates the room.- We have lost something: the attendees that the user set on the card no longer reach the form, which starts with 1. They are not a resource identifier but an option of the screen; their place is the query (
?attendees=4), which we will look at in 04-05.
8.6 The 404 shows the address
Since NotFoundView is rendered both from the catch-all route and from the spec sheet, let's make it show which address does not exist. Here we do use useRoute(), because the address is not the view's data but data about the navigation:
<script setup>
import { useRoute } from 'vue-router'
const route = useRoute()
</script>
<template>
<section class="not-found">
<h2>This page does not exist</h2>
<p>There is nothing at <code>{{ route.fullPath }}</code>. The link may be mistyped, or the page may have moved.</p>
<!-- links to the home page and the catalogue, no changes -->
</section>
</template>8.7 Try it
- Spec sheet. In the catalogue, click the name "Néctar Room": the URL changes to
/rooms/nectar, "Loading the room…" appears and then the spec sheet. Copy the URL and open it in another tab: the same spec sheet. - Reuse. In "Other rooms", click "Polen Room". With Vue DevTools open, observe that the
RoomDetailViewcomponent is not mounted again (its instance does not change) and that itsidprop changes to'polen'. Temporarily comment out thewatchand replace it with anonMountedthat callsloadRoom(id): the URL changes, but the spec sheet stays on Néctar. Undo the change. - Cancellation. With the network set to "Slow 3G", click several rooms in a row in "Other rooms": only the last one is shown. No errors from the cancelled requests appear in the console.
- A 404 that keeps the URL. Type
/rooms/basement: the 404 page appears with the text "There is nothing at /rooms/basement" and the URL does not change. Type/rooms/123: the 404 too, but this time through the catch-all route (the regular expression does not accept it), with no request to the API. Check it in the routes tab in DevTools. - An error other than 404. Reload several spec sheets until the simulated API fails (10% of the time): you see the error with "Retry", not the 404.
- Booking. On Néctar's spec sheet, click "Book this room": the form opens at
/book/nectarwith Néctar chosen. Reload: it is still on Néctar. On the Enjambre Auditorium's spec sheet (under maintenance), there is no booking link. - From the catalogue. Click "Book" on the Polen card: the notice links to
/book/polen.
Common Mistakes and Tips
- Storing a param in a constant (
const id = route.params.id) and expecting it to update. Read throughroute, in acomputedor in awatchgetter; or, better still, receive it as a prop. - Loading the data only in
onMountedin a view with params. When going from one room to another, the view is reused and is not mounted again. Usewatchwithimmediate. - Forgetting that params are strings.
route.params.floor === 2is always false. Convert them in thepropsfunction or when you use them. - Building URLs by hand (
:to="`/rooms/${room.id}`"): special characters are not encoded and, if the route changes, you have to find every link. Usename+params. - Passing
paramstogether withpath({ path: '/rooms', params: { id: 'nectar' } }). Withpath, theparamsare ignored. Usename+paramsor write the completepath. - Redirecting to an error URL when the item does not exist. The user loses the address they typed and the Back button becomes confusing. Render the 404 in place.
- Tip: ask yourself what identifies what is being shown on screen. If it is a resource (a room, an invoice), it goes in a route param; if it is a display option (filters, sort order, results page, proposed attendees), it goes in the query.
Exercises
Exercise 1. Add a link to each room's spec sheet in TableView's name column. Then work out the alternative without a RouterLink in RoomCard: remove the link from the name and make GridView add, through the #actions slot, a "View spec sheet" link next to the usual buttons. What advantage does each approach have?
Exercise 2. Create the route /rooms/floor/:number(\\d) (name rooms-floor) with a FloorRoomsView view that receives number as a number (not as a string) and lists the rooms on that floor using fetchRooms({ floor: number }). The view must have "Floor 1", "Floor 2" and "Floor 3" links and load the right rooms when moving from one to another. Why does this route not clash with /rooms/:id([a-z-]+)? What happens with /rooms/floor/7?
Exercise 3. This component always shows the first room visited. Explain why and fix it in two ways: with useRoute() and with props.
<script setup>
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { fetchRoom } from '@/api/rooms.js'
const { params } = useRoute()
const room = ref(null)
fetchRoom(params.id).then((result) => (room.value = result))
</script>Solutions
Solution 1.
<!-- TableView.vue, in the name cell -->
<td>
<RouterLink :to="{ name: 'room-detail', params: { id: room.id } }">{{ room.name }}</RouterLink>
</td><!-- GridView.vue: for available rooms, actions of its own -->
<template v-if="!room.available" #actions>
<p class="notice">Under maintenance: not accepting bookings.</p>
</template>
<template v-else #actions="{ attendees }">
<RouterLink :to="{ name: 'room-detail', params: { id: room.id } }">View spec sheet</RouterLink>
<BaseButton variant="secondary" @click="emit('select', room.id)">Select</BaseButton>
<BaseButton @click="emit('book', { roomId: room.id, attendees })">Book</BaseButton>
</template>With the link inside RoomCard, every card, wherever it is used, leads to the spec sheet: consistent and with no repeated code, at the cost of the card depending on the router. With the slot, the card remains independent and each context decides; the price is repeating the default buttons in the slot. Both approaches are valid; what matters is choosing one consciously.
Solution 2.
// src/router/index.js
{
path: '/rooms/floor/:number(\\d)',
name: 'rooms-floor',
component: () => import('@/views/FloorRoomsView.vue'),
props: (route) => ({ number: Number(route.params.number) })
},<!-- src/views/FloorRoomsView.vue -->
<script setup>
import { ref, watch, onWatcherCleanup } from 'vue'
import { fetchRooms } from '@/api/rooms.js'
const { number } = defineProps({ number: { type: Number, required: true } })
const floorRooms = ref([])
const loading = ref(false)
watch(
() => number,
async (floor) => {
const controller = new AbortController()
onWatcherCleanup(() => controller.abort())
loading.value = true
try {
floorRooms.value = await fetchRooms({ floor }, { signal: controller.signal })
} catch (e) {
if (e.name === 'AbortError') return
floorRooms.value = []
}
loading.value = false
},
{ immediate: true }
)
</script>
<template>
<h2>Rooms on floor {{ number }}</h2>
<nav>
<RouterLink v-for="n in 3" :key="n" :to="{ name: 'rooms-floor', params: { number: n } }">
Floor {{ n }}
</RouterLink>
</nav>
<p v-if="loading">Loading…</p>
<ul v-else>
<li v-for="room in floorRooms" :key="room.id">
<RouterLink :to="{ name: 'room-detail', params: { id: room.id } }">{{ room.name }}</RouterLink>
</li>
</ul>
</template>fetchRooms compares room.floor === floor with strict equality: with the string '2' it would find nothing; that is why the props function converts with Number. When linking, you can pass number: n as a number: the router converts it to text for the URL. It does not clash with /rooms/:id([a-z-]+) because that route has one segment after /rooms/ and only accepts letters; floor/2 is two segments. /rooms/floor/7 fits the shape, because \\d accepts any digit, and shows "Rooms on floor 7" with an empty list. To send it to the 404, restrict the expression: :number([1-3]).
Solution 3. const { params } = useRoute() destructures the route object once: params is the params object at that moment. In addition, the request is made only once, in setup, and when moving to another room the view is reused and setup does not run again.
// With useRoute(): always read through route, in a watch
const route = useRoute()
const room = ref(null)
watch(
() => route.params.id,
async (id) => {
room.value = await fetchRoom(id)
},
{ immediate: true }
)// With props (and props: true on the route): the view does not depend on the router
const { id } = defineProps({ id: { type: String, required: true } })
const room = ref(null)
watch(
() => id,
async (roomId) => {
room.value = await fetchRoom(roomId)
},
{ immediate: true }
)For a complete version, add cancellation with AbortController and the loading and error states, as in RoomDetailView.
Conclusion
Dynamic segments (/rooms/:id) let a single route serve every item in a collection. You have learnt to read params with useRoute() (always through the reactive route object, never by destructuring it), to receive them as props with props: true, in object mode or in function mode to convert types, and to deal with the case where only the param changes and the view is reused: with a watch with immediate (the default option), with the onBeforeRouteUpdate guard or, as a last resort, with a key on <RouterView>. You know about optional params (?), repeatable params (+, *) and params with regular expressions, and you know how to show a 404 that keeps the URL when the item does not exist. Colmena now has a spec sheet for each room at /rooms/:id (RoomDetailView), linked from the cards and with navigation between rooms, and the form receives its room from the URL, /book/:roomId, which has made it possible to remove the temporary proposal from App.vue.
The application now has several screens at the same level, all inside App.vue's frame. But some screens have fixed parts and variable parts of their own: the member's personal area will have a permanent side menu and, next to it, the profile, the bookings or the invoices. That is what routes within routes are for, and we will study them in Nested Routes.
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
