Dynamic routes and params
Matching many URLs with one route using :params, reading them reactively, reacting when only the param changes, passing them as props, and query strings.
Dynamic routes and params
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A path segment starting with a colon, like `/users/:id`, is a param: one route record matches every user, and the matched value appears as a string on `route.params.id`.
- Going from `/users/1` to `/users/2` reuses the same component instance, so `onMounted` does not run again; react to the change with `watch(() => route.params.id, ...)` or `onBeforeRouteUpdate`.
- Destructuring `const { id } = route.params` copies the value once and stops tracking it; read `route.params.id` inside a getter, `computed`, or template instead.
- `props: true` on the route record passes params to the component as props, so the component declares `defineProps` and no longer depends on the router at all.
- Params can be constrained and shaped: `:id(\d+)` for digits only, `:slug?` for optional, `:path+` or `:path*` for repeated segments, and `/:pathMatch(.*)*` for a catch-all 404.
- Query strings (`?sort=price`) are not part of matching; they arrive as `route.query`, and `router.push({ query })` updates them so filter state survives refresh and sharing.
One route, many URLs
An online shop has thousands of products. Nobody writes a route per product. You want one rule: “anything that looks like /products/<something> renders ProductDetail, and tell it which something.” That rule is a dynamic route, and the “something” is a param.
const routes = [
{ path: '/products', name: 'products', component: ProductList },
{ path: '/products/:id', name: 'product', component: ProductDetail },
{ path: '/users/:username/posts/:postId', name: 'post', component: PostView },
]
A segment that begins with : matches any single path segment. The matched text lands on route.params under that name, always as a string:
| pattern | URL | route.params |
|---|---|---|
/products/:id |
/products/42 |
{ id: '42' } |
/users/:username/posts/:postId |
/users/ada/posts/7 |
{ username: 'ada', postId: '7' } |
To link to one, pass the params with the route name and let the router build the URL:
<RouterLink :to="{ name: 'product', params: { id: product.id } }">
{{ product.title }}
</RouterLink>
Reading params without losing reactivity
Inside the routed component, useRoute() returns the current route, and it is reactive. That means how you read it matters.
<script setup>
import { computed } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
// tracked: re-evaluates whenever the param changes
const productId = computed(() => Number(route.params.id))
// NOT tracked: a plain string, frozen at setup time
const { id } = route.params
</script>
<template>
<h1>Product {{ productId }}</h1>
</template>
This is the same rule the reactivity group taught about reactive objects. Destructuring copies values out of the proxy, and the copies don’t know the source changed. It matters here because of the next point.
The reused-component trap
Go from /products/1 to /products/2. Both URLs match the same record, so Vue Router does the efficient thing: it keeps the existing ProductDetail instance and only updates route.params. Nothing is unmounted and nothing is mounted again. So onMounted doesn’t fire a second time. Neither does setup code that read the param once.
Picture a hotel room. When a new guest checks in, staff don’t demolish and rebuild the room. They change the name on the booking. A component that only looked at the name tag on day one never notices the change.
The fix is to treat the param as a reactive source and watch it:
<script setup>
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
const product = ref(null)
const error = ref(null)
watch(
() => route.params.id,
async (id) => {
error.value = null
product.value = null
try {
product.value = await fetchProduct(id)
} catch (e) {
error.value = e
}
},
{ immediate: true }, // also run for the first id
)
</script>
The getter () => route.params.id makes Vue track exactly that field, and immediate: true covers the initial load. The alternative is the in-component guard onBeforeRouteUpdate, which runs before the param change is confirmed and can cancel it. It is covered with the other guards in navigation guards.
A third option is to force a fresh instance per URL by keying the routed component on the path:
<RouterView v-slot="{ Component, route }">
<component :is="Component" :key="route.path" />
</RouterView>
That throws away the reuse optimization, so save it for components where resetting all local state is genuinely what you want. Request lifecycles, races, and caching are their own subject in data fetching in Vue.
Params as props
A component that calls useRoute() only works under a router, on a URL with the right param. Usually that’s fine. When it isn’t — a card reused in a modal, a component you want to unit-test without a router — let the router pass params in as props:
{ path: '/products/:id', component: ProductDetail, props: true }
<!-- ProductDetail.vue -->
<script setup>
const props = defineProps({ id: { type: String, required: true } })
</script>
props: true maps route.params straight onto props. You can also give an object for static props, or a function when you need to convert types or pull from the query:
{
path: '/search',
component: SearchResults,
props: (route) => ({ q: route.query.q ?? '', page: Number(route.query.page ?? 1) }),
}
Props from the router are reactive like any other props. When the param changes on a reused instance, the prop updates, and you can watch(() => props.id, ...) the same way.
Shaping what a param matches
Vue Router’s path syntax goes beyond a bare :name:
const routes = [
// only digits: /orders/123 matches, /orders/abc does not
{ path: '/orders/:orderId(\\d+)', component: Order },
// optional: matches /docs and /docs/intro
{ path: '/docs/:page?', component: Docs },
// one or more segments: /files/a/b/c → params.path = ['a', 'b', 'c']
{ path: '/files/:path+', component: FileBrowser },
// catch-all 404, matches anything left over
{ path: '/:pathMatch(.*)*', name: 'not-found', component: NotFound },
]
The parentheses hold a custom regex (backslashes doubled because it’s inside a JS string). ? makes a param optional. + and * make it repeatable — one-or-more and zero-or-more — and turn the param into an array. The catch-all combines both ideas. (.*) lets the param swallow slashes, and the trailing * stores the segments as an array. You don’t need to order routes carefully: the router ranks records by specificity, so /orders/:orderId(\\d+) beats a looser pattern regardless of where it sits in the array.
Query strings
Params are part of the path and part of matching. The query string isn’t: /products?sort=price&page=2 matches the plain /products route, and the extras show up as route.query, an object of strings.
Query params suit state that should survive a refresh or a shared link without being part of the page’s identity: filters, sort order, the current tab. Write them with router.push or router.replace:
function setSort(sort) {
// keep other query values, replace the history entry so Back isn't flooded
router.replace({ query: { ...route.query, sort } })
}
Read them the same way as params — through route.query.sort inside a computed or a watched getter — and remember they arrive as strings (or arrays, if a key repeats).
With file-based routing in Vue Router 5, src/pages/products/[id].vue declares the same :id param. The Volar plugin then gives route.params.id a real type instead of a loose string map, which TypeScript with Vue picks up later.
What the video covers
Laith Harb’s routing course starts here at 33:00, “Dynamic Routing”. He builds a /car/:id route for a car-listings app, reads the id with useRoute() in <script setup>, and finds the matching car. He then changes pages from code with router.push, adds a /:pathMatch(.*)* catch-all, and spends a long section syncing make-and-price filters into route.query and reading them back. All of it uses the current API. One habit in his code is worth noticing rather than copying: CarView destructures const { id } = route.params once in setup. It works in his demo because you always arrive from the home page, which creates a fresh instance. Link from one car straight to another and the page would go stale. The watched-getter pattern above is the fix. The video doesn’t cover props: true or param modifiers, so those sections are this lesson’s own.
Check yourself
A `UserProfile` component loads data in `onMounted` using `route.params.id`. Clicking a link from `/users/1` to `/users/2` changes the URL but the page still shows user 1. Why, and what are two fixes?
Both URLs match the same route record, so Vue Router reuses the existing `UserProfile` instance instead of unmounting it, and `onMounted` never runs again. Fix it by watching the param — `watch(() => route.params.id, load, { immediate: true })` — or by reloading inside `onBeforeRouteUpdate((to) => load(to.params.id))`. Forcing a remount with a `:key` on the routed component also works, at the cost of rebuilding it.
What is wrong with `const { id } = useRoute().params` at the top of `<script setup>`?
`route.params` is reactive, but destructuring reads `id` once and stores a plain string in a local constant. When the param changes while the component is reused, the constant keeps the old value and nothing that depends on it updates. Read `route.params.id` inside a getter, `computed`, or the template so Vue tracks it.
What does `props: true` on a route record do, and why would you want it?
It passes the route's `params` to the routed component as props, so `/users/:id` hands the component an `id` prop. The component declares `defineProps({ id: String })` and never calls `useRoute()`, which means it can be reused outside that route and tested by passing a prop instead of setting up a router.
How does the route path `/:pathMatch(.*)*` work as a 404 page?
`pathMatch` is just a param name. The `(.*)` custom regex lets it match any characters including slashes, and the trailing `*` makes it repeatable, so it matches any path at all and stores the segments as an array. Because the router ranks more specific paths higher, every real route still wins, and only unmatched URLs fall through to this record.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.