Skip to content

Route Parameters and useRoute

Route parameters let a single route definition handle many different URLs. /person/alice, /person/bob, and /person/carol all match the route /person/:id — only the :id segment differs.

{
path: '/:id',
name: 'person',
component: () => import('../views/PersonDetailView.vue'),
}

The :id segment is a named parameter. Any URL like /abc-123, /xyz-456, or /any-value matches and captures that value as id.

Inside a view component, useRoute() gives you the current route object:

PersonDetailView.vue
<script setup lang="ts">
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import { useFamilyStore } from '../stores/familyStore'
import { storeToRefs } from 'pinia'
const route = useRoute()
const store = useFamilyStore()
const { people } = storeToRefs(store)
const id = route.params.id as string
const person = computed(() =>
people.value.find(p => p.id === id)
)
</script>
<template>
<div v-if="person">
<h1>{{ person.name }}</h1>
</div>
<p v-else>Person not found.</p>
</template>

route.params.id is always a string (or string[] if the param is optional). The as string cast is safe when the route guarantees a single value.

  • route.params — path parameters from /edit/:idroute.params.id
  • route.query — query string from /?search=aliceroute.query.search

FamilyTree uses only route.params — no query strings.

If a component stays mounted while params change (e.g., navigating from /person/alice to /person/bob), the component doesn’t remount — Vue reuses it. Use watch to respond to the param change:

watch(
() => route.params.id,
(newId) => {
// load new data for newId
}
)

Or add the :key="route.params.id" attribute to <RouterView> to force remounting:

<RouterView :key="$route.params.id" />

FamilyTree doesn’t need this — PersonDetailView derives everything from route.params.id via a computed that re-runs automatically when the route changes.

  1. In PersonDetailView.vue, use useRoute() to read the id param.
  2. Find the matching person in the store by that id.
  3. Display the person’s name and a “Person not found” fallback.
  4. Navigate to /some-unknown-id in the browser. Confirm the fallback renders.
  • :paramName in a route path captures a dynamic segment.
  • useRoute() returns the current route object in a component.
  • route.params.paramName reads the captured value — always a string.
  • route.query.key reads query string values.
  • If params change without remounting the component, use watch(() => route.params.id, ...) to respond.