We use cookies to enhance your experience on the site
CodeWorlds

Dynamic Routes

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:

1const routes = [
2  {
3    path: '/system/:id',
4    name: 'system-detail',
5    component: SystemDetail
6  },
7  {
8    path: '/crew/:name',
9    name: 'crew-detail',
10    component: CrewDetail
11  },
12  // Multiple parameters
13  {
14    path: '/module/:moduleId/system/:systemId',
15    name: 'module-system',
16    component: ModuleSystem
17  }
18]

Reading Parameters - useRoute()

The

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

1<script setup>
2import { useRoute } from 'vue-router'
3
4const route = useRoute()
5
6// Access to parameters
7console.log(route.params.id) // e.g., '42'
8console.log(route.path)      // e.g., '/system/42'
9console.log(route.name)      // e.g., 'system-detail'
10</script>
11
12<template>
13  <div>
14    <h1>System #{{ route.params.id }}</h1>
15  </div>
16</template>

Navigation with Parameters

1<template>
2  <div v-for="system in systems" :key="system.id">
3    <!-- String URL -->
4    <RouterLink :to="\`/system/\${system.id}\`">
5      {{ system.name }}
6    </RouterLink>
7
8    <!-- Object notation (recommended) -->
9    <RouterLink :to="{ name: 'system-detail', params: { id: system.id } }">
10      {{ system.name }}
11    </RouterLink>
12  </div>
13</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:

1<script setup>
2import { ref, watch } from 'vue'
3import { useRoute } from 'vue-router'
4
5const route = useRoute()
6const systemData = ref(null)
7
8watch(
9  () => route.params.id,
10  (newId) => {
11    // Load new system data
12    loadSystem(newId)
13  },
14  { immediate: true }
15)
16</script>

Query Parameters

Query parameters are the part of the URL after the

?
character:

1<script setup>
2import { useRoute, useRouter } from 'vue-router'
3
4const route = useRoute()
5const router = useRouter()
6
7// URL: /systems?module=habitat&sort=priority
8console.log(route.query.module) // 'habitat'
9console.log(route.query.sort)   // 'priority'
10
11// Navigation with query
12function filterByModule(module) {
13  router.push({
14    name: 'systems',
15    query: { module, sort: 'priority' }
16  })
17}
18</script>

Optional and Validated Parameters

1const routes = [
2  // Optional parameter with ?
3  { path: '/system/:id?' },
4
5  // Regex - numbers only
6  { path: '/system/:id(\\d+)' },
7
8  // Repeatable parameter
9  { path: '/modules/:ids+' }
10]
Go to CodeWorlds