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.
Defining a parameterized route
Section titled “Defining a parameterized route”{ 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.
Accessing params with useRoute
Section titled “Accessing params with useRoute”Inside a view component, useRoute() gives you the current route object:
<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 vs route.query
Section titled “route.params vs route.query”route.params— path parameters from/edit/:id→route.params.idroute.query— query string from/?search=alice→route.query.search
FamilyTree uses only route.params — no query strings.
Watching param changes
Section titled “Watching param changes”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.
Exercise
Section titled “Exercise”- In
PersonDetailView.vue, useuseRoute()to read theidparam. - Find the matching person in the store by that id.
- Display the person’s name and a “Person not found” fallback.
- Navigate to
/some-unknown-idin the browser. Confirm the fallback renders.
:paramNamein a route path captures a dynamic segment.useRoute()returns the current route object in a component.route.params.paramNamereads the captured value — always a string.route.query.keyreads query string values.- If params change without remounting the component, use
watch(() => route.params.id, ...)to respond.