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

  1. Dynamic segments
  2. Reading params with useRoute()
  3. Receiving params as props
  4. When only the param changes: the component is reused
  5. Optional and repeatable params and params with a regular expression
  6. Table of patterns
  7. When the item does not exist: a 404 that keeps the URL
  8. Case study: each room's spec sheet and the room in the form's URL

  1. Dynamic segments

A dynamic segment is written with a colon in front of its name:

{ path: '/rooms/:id', name: 'room-detail', component: RoomDetailView }
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/photos does not match.
  • Its value is always a string. In /invoices/141, the param would be '141', not 141.
  • There can be several in one route: /floors/:floor/rooms/:id produces { 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.

  1. Reading params with 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>, like inject (in fact, under the hood it uses inject).
  • The route object is reactive, but its properties are replaced on every navigation. If you write const id = route.params.id or const { params } = route, you store the value at that moment and it will not be updated. Always read through route (route.params.id) in the template, in a computed or in a watch getter.
  • In the template you have $route without needing to call useRoute(), and in the Options API, this.$route. It is the same object.

  1. 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:

{ path: '/rooms/:id', name: 'room-detail', component: RoomDetailView, props: true }
<!-- 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).

  1. 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) and from (the origin route). You have to read the param from to: 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>:

<RouterView :key="$route.fullPath" />

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

  1. 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 floors

When 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 the path is 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 props in 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".

  1. 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.

  1. 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.

  1. 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/123 does not even reach the view: it goes straight to the router's 404.
  • props: true: the views will receive id and roomId as props.
  • By changing /book to /book/:roomId, any link to { name: 'book' } without params will throw an error. There is only one, the one in RoomsView; 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:

  • id arrives as a prop (thanks to props: true): the view does not import anything from vue-router. It could be shown in a modal by passing it id="nectar".
  • The watch with immediate loads the room when the view is mounted and every time id changes, 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/basement is 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 book route. 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, as BookingForm already did. When one is clicked, the route changes but the view is reused: the watch is 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>
/* In the <style scoped> of RoomCard.vue */
.card__link {
  color: inherit;
}

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:

// App.vue
provide(BOOKINGS_KEY, {
  bookings: readonly(bookings),
  recordBooking
})

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" />
  • BookingForm does not change: it still receives roomId as a prop. If the user goes from /book/panal to /book/polen, BookingView is reused, its prop changes, and the watch that 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

  1. 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.
  2. Reuse. In "Other rooms", click "Polen Room". With Vue DevTools open, observe that the RoomDetailView component is not mounted again (its instance does not change) and that its id prop changes to 'polen'. Temporarily comment out the watch and replace it with an onMounted that calls loadRoom(id): the URL changes, but the spec sheet stays on Néctar. Undo the change.
  3. 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.
  4. 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.
  5. 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.
  6. Booking. On Néctar's spec sheet, click "Book this room": the form opens at /book/nectar with Néctar chosen. Reload: it is still on Néctar. On the Enjambre Auditorium's spec sheet (under maintenance), there is no booking link.
  7. 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 through route, in a computed or in a watch getter; or, better still, receive it as a prop.
  • Loading the data only in onMounted in a view with params. When going from one room to another, the view is reused and is not mounted again. Use watch with immediate.
  • Forgetting that params are strings. route.params.floor === 2 is always false. Convert them in the props function 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. Use name + params.
  • Passing params together with path ({ path: '/rooms', params: { id: 'nectar' } }). With path, the params are ignored. Use name + params or write the complete path.
  • 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.

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