Vue.js course ยท Module 10: Vue Router

Dynamic Routes

2 min read ยท
In this lesson6

Each NOVA LAB base module has its unique identifier. Similarly, we can create dynamic paths in the application - routes that accept parameters in the URL.

Route Params

A dynamic parameter is defined with a colon : in the path:

const routes = [
  {
    path: '/system/:id',
    name: 'system-detail',
    component: SystemDetail
  },
  {
    path: '/crew/:name',
    name: 'crew-detail',
    component: CrewDetail
  },
  // Multiple parameters
  {
    path: '/module/:moduleId/system/:systemId',
    name: 'module-system',
    component: ModuleSystem
  }
]

Reading Parameters - useRoute()

The useRoute() composable gives access to information about the current route, including parameters:

<script setup>
import { useRoute } from 'vue-router'

const route = useRoute()

// Access to parameters
console.log(route.params.id) // e.g., '42'
console.log(route.path)      // e.g., '/system/42'
console.log(route.name)      // e.g., 'system-detail'
</script>

<template>
  <div>
    <h1>System #{{ route.params.id }}</h1>
  </div>
</template>
<template>
  <div v-for="system in systems" :key="system.id">
    <!-- String URL -->
    <RouterLink :to="`/system/${system.id}`">
      {{ system.name }}
    </RouterLink>

    <!-- Object notation (recommended) -->
    <RouterLink :to="{ name: 'system-detail', params: { id: system.id } }">
      {{ system.name }}
    </RouterLink>
  </div>
</template>

Reactivity to Params Changes

When you change a parameter within the same route, the component is NOT unmounted. Use watch to react to changes:

<script setup>
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()
const systemData = ref(null)

watch(
  () => route.params.id,
  (newId) => {
    // Load new system data
    loadSystem(newId)
  },
  { immediate: true }
)
</script>

Query Parameters

Query parameters are the part of the URL after the ? character:

<script setup>
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

// URL: /systems?module=habitat&sort=priority
console.log(route.query.module) // 'habitat'
console.log(route.query.sort)   // 'priority'

// Navigation with query
function filterByModule(module) {
  router.push({
    name: 'systems',
    query: { module, sort: 'priority' }
  })
}
</script>

Optional and Validated Parameters

const routes = [
  // Optional parameter with ?
  { path: '/system/:id?' },

  // Regex - numbers only
  { path: '/system/:id(\\d+)' },

  // Repeatable parameter
  { path: '/modules/:ids+' }
]
Code for this lesson: App.vue
<script setup>
import { ref } from 'vue'

// Simulation of nested routes
const currentPath = ref('/mission-control')
const sidebarItems = [
  { path: '/mission-control', label: 'Overview', name: 'overview' },
  { path: '/mission-control/systems', label: 'Systems', name: 'systems' },
  { path: '/mission-control/crew', label: 'Crew', name: 'crew' }
]

function navigate(path) {
  currentPath.value = path
}

const isActive = (path) => currentPath.value === path
</script>

<template>
  <div class="nova-lab">
    <h1>NOVA LAB - Nested Routes</h1>

    <div class="layout">
      <aside class="sidebar">
        <h3>Mission Control Center</h3>
        <nav>
          <a
            v-for="item in sidebarItems"
            :key="item.path"
            @click.prevent="navigate(item.path)"
            :class="{ active: isActive(item.path) }"
            href="#"
          >
            {{ item.label }}
          </a>
        </nav>

        <div class="config-info">
          <pre>
children: [
  { path: '', component: Overview },
  { path: 'systems', component: Systems },
  { path: 'crew', component: Crew }
]</pre>
        </div>
      </aside>

      <main class="content">
        <div v-if="currentPath === '/mission-control'" class="child-page">
          <h2>Mission Overview</h2>
          <p>Default view (path: '')</p>
          <div class="stats">
            <div class="stat">
              <span class="label">Mission status</span>
              <span class="value ok">ACTIVE</span>
            </div>
            <div class="stat">
              <span class="label">Mission day</span>
              <span class="value">247</span>
            </div>
            <div class="stat">
              <span class="label">Crew</span>
              <span class="value">12 people</span>
            </div>
          </div>
        </div>

        <div v-else-if="currentPath === '/mission-control/systems'" class="child-page">
          <h2>Base Systems</h2>
          <p>Child route: path: 'systems'</p>
          <ul class="systems-list">
            <li>Oxygen Generator - ONLINE</li>
            <li>Water Recycler - ONLINE</li>
            <li>Power Grid - WARNING</li>
            <li>Communications - ONLINE</li>
          </ul>
        </div>

        <div v-else-if="currentPath === '/mission-control/crew'" class="child-page">
          <h2>Crew</h2>
          <p>Child route: path: 'crew'</p>
          <ul class="crew-list">
            <li>Dr. Nova - Commander</li>
            <li>Eng. Kowalski - Systems</li>
            <li>Dr. Chen - Science</li>
          </ul>
        </div>
      </main>
    </div>
  </div>
</template>

<style scoped>
.nova-lab {
  background: #0a0e27;
  color: #00ff88;
  min-height: 100vh;
  padding: 20px;
  font-family: monospace;
}
h1 { color: #00ffff; margin-bottom: 15px; }
h2 { color: #00b4d8; }
h3 { color: #00ffff; margin-bottom: 10px; }
p { color: #c0c0c0; }
.layout {
  display: grid;
  grid-template-columns: 220px 1fr;
  gap: 15px;
}
.sidebar {
  background: rgba(0, 180, 216, 0.05);
  border: 1px solid #1a1e37;
  padding: 15px;
}
.sidebar nav { display: flex; flex-direction: column; gap: 5px; }
.sidebar a {
  color: #00ff88;
  text-decoration: none;
  padding: 8px;
  border-left: 2px solid transparent;
  cursor: pointer;
}
.sidebar a.active {
  border-left-color: #00ffff;
  color: #00ffff;
  background: rgba(0, 255, 255, 0.05);
}
.config-info { margin-top: 15px; }
.config-info pre {
  font-size: 10px;
  color: #888;
  background: #1a1e37;
  padding: 8px;
}
.content {
  background: rgba(0, 180, 216, 0.05);
  border: 1px solid #1a1e37;
  padding: 15px;
}
.child-page { min-height: 200px; }
.stats { display: flex; gap: 15px; margin-top: 15px; flex-wrap: wrap; }
.stat {
  background: #1a1e37;
  padding: 10px 15px;
  border: 1px solid #00b4d8;
}
.stat .label { display: block; color: #888; font-size: 11px; }
.stat .value { display: block; color: #00ff88; font-size: 18px; margin-top: 4px; }
.stat .value.ok { color: #00ff88; }
ul { color: #c0c0c0; margin-top: 10px; }
li { margin: 5px 0; }
</style>

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. How do you define a dynamic parameter in a Vue Router path?

  2. 2. How do you access the current route's parameters in the Composition API?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Create a route /system/:id and a component that reads params.id via useRoute().

  • Vertical ordering

    Arrange the steps for handling a dynamic route:

  • Click in order

    Arrange the programmatic navigation with parameters:

  • Code editor

    Navigate with query params and read them in a component via useRoute().query.

  • Horizontal ordering

    Arrange the RouterLink syntax with a dynamic parameter:

  1. QuestionDefining a Dynamic Parameter
  2. QuestionThe useRoute Composable
  3. Coding taskPractice: Route with a Dynamic Parameter
  4. Put in orderDynamic Route Flow
  5. QuestionQuery Parameters
  6. Click in orderNavigation with Parameters
  7. Coding taskPractice: Query Parameters and Filtering
  8. Put in orderRouterLink Syntax with a Parameter

Useful articles