Vue Router 03 🧭 Dynamic Routes & Matching Syntax — Route Params, Regex, and Catch-alls
Static routing is sufficient for simple pages like “About” or “Contact,” but most modern applications require dynamic paths to represent data-driven resources. A social media platform doesn’t create a unique route for every user; instead, it defines a single dynamic pattern that can capture a username or ID from the URL and pass it into a component. Vue Router provides a powerful pattern-matching engine that allows developers to define these dynamic segments, validate them using regular expressions, and handle optional or repeating URL parts.
In Vue Router 4, the route matching system was overhauled to be more predictable and type-safe. It uses a ranking system to determine which route should match when multiple patterns overlap, moving away from the “first-match-wins” logic of older versions. This system also introduces a more explicit syntax for “catch-all” routes, which are essential for handling 404 “Not Found” pages. By mastering dynamic segments, you can create flexible architectures that handle everything from simple IDs to complex, multi-segment file paths.
This chapter covers the syntax for defining dynamic route parameters and how to access them within your components using both the Options API and the Composition API. We will also explore advanced matching techniques, including using regex to restrict parameters to specific formats, creating optional or repeatable segments, and implementing the universal catch-all route for error handling.
Key point: Dynamic segments are denoted by a colon (:) in the route path; they capture values from the URL into the $route.params object, allowing a single component to render content based on the captured data.
Why exists
The Data-Driven Identification problem.
In an application with thousands of products or users, it is impossible to hardcode a route for every item. Dynamic routes allow you to define a template path like /user/:id. This acts as a placeholder that matches any value in that position, allowing one component to handle an infinite number of specific resources.
The Input Validation problem.
Not all dynamic values are valid. For example, a user ID might always be numeric, while a category slug must be alphanumeric. Vue Router’s matching syntax allows you to attach regular expressions directly to parameters. This ensures that the router only matches a route if the URL segment meets specific criteria, preventing the application from attempting to load data for malformed IDs.
The Segment Flexibility problem.
Sometimes a piece of the URL is optional, such as a localized prefix (e.g., /en/home vs /home) or an optional search query embedded in the path. Matching syntax provides quantifiers like ?, *, and + to define whether a segment is required, optional, or can appear multiple times.
The Deeply Nested Resource problem.
When dealing with file systems or hierarchical categories, you may not know how many segments the URL will have (e.g., /files/docs/work/project/memo.pdf). Repeatable dynamic segments allow the router to capture an arbitrary number of path segments into a single array, simplifying the logic for recursive or deeply nested structures.
The Unexpected Navigation problem.
Users often type URLs manually or click on broken links. Without a catch-all mechanism, the application would simply fail to render anything or show a blank screen. The matching syntax provides a way to define a “fallback” route that matches any URL not explicitly defined, allowing you to show a friendly 404 page.
a. Dynamic Segments and $route.params
The most common use of dynamic routing is the single parameter. By prefixing a segment with a colon (:), you tell Vue Router to treat that part of the URL as a variable. When a user visits a path that matches this pattern, the value in that position is extracted and placed into the params object of the current route.
// router/index.ts
const routes = [
{
// :id is the dynamic segment
path: '/user/:id',
name: 'user-detail',
component: () => import('../views/UserDetail.vue')
}
];
Inside the component, you can access this parameter to fetch data from an API or update the UI. If you are using the Options API, the parameter is available at this.$route.params.id. In the Composition API, you use the useRoute hook to access the reactive route object.
<!-- UserDetail.vue -->
<script setup>
import { useRoute } from 'vue-router';
import { onMounted, ref, watch } from 'vue';
const route = useRoute();
const userData = ref(null);
const fetchUser = async (id) => {
// Simulate API call
userData.value = await api.getUser(id);
};
// Initial load
onMounted(() => fetchUser(route.params.id));
// CRITICAL: Watch the params for changes!
// If navigating from /user/1 to /user/2, the component is reused,
// so onMounted won't fire again.
watch(() => route.params.id, (newId) => {
fetchUser(newId);
});
</script>
A common mistake is forgetting that Vue Router reuses component instances when only the parameters change (e.g., navigating from /user/1 to /user/2). Because the component isn’t destroyed and recreated, lifecycle hooks like onMounted do not run a second time. You must watch the route.params to respond to these changes, or use the beforeRouteUpdate navigation guard.
b. Matching Syntax: Regex and Quantifiers
Vue Router 4 allows you to use regular expressions within the path definition to provide fine-grained control over what a segment can match. This is done by adding the regex in parentheses immediately after the parameter name. This is extremely useful for distinguishing between routes that might otherwise look identical to a simple matcher.
const routes = [
// Matches /user/123 but NOT /user/alice
{
path: '/user/:id(\\d+)',
component: UserById
},
// Matches /user/alice but NOT /user/123
{
path: '/user/:username',
component: UserByUsername
}
];
In the example above, the order of routes matters less than in previous versions because the :id(\\d+) route is more specific and will be ranked higher for numeric inputs. Beyond basic regex, you can use quantifiers to change how many segments a parameter can capture:
- Optional (
?): The segment may or may not be present. - Repeatable (
*): Zero or more segments (captured as an array). - Required Repeatable (
+): One or more segments (captured as an array).
const routes = [
// Optional: Matches /ship and /ship/express
{ path: '/ship/:method?', component: Shipping },
// Repeatable: Matches /gallery, /gallery/summer, /gallery/summer/vacation
// params.images will be ['summer', 'vacation']
{ path: '/gallery/:images*', component: Gallery }
];
Using these quantifiers allows you to build extremely flexible path structures. For instance, the * quantifier is perfect for breadcrumb systems or file explorers where the depth of the navigation is dynamic.
c. The Catch-All (404) Route
In every application, you need a way to handle URLs that don’t match any of your defined routes. In Vue Router 4, this is handled by a special dynamic segment using a custom regex that matches everything. The standard convention is to name this parameter pathMatch.
const routes = [
// ... all other routes ...
// Catch-all route
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: () => import('../views/NotFound.vue')
}
];
The syntax :pathMatch(.*)* breaks down as follows:
:pathMatch: The name of the parameter.(.*): A regex that matches any character.*: A quantifier that allows this to match multiple segments (e.g.,/some/non-existent/path).
Because of Vue Router’s ranking system, this route will naturally have the lowest priority because it is the most general. However, it is still standard practice to place it at the very end of your routes array. Within the NotFound.vue component, you can actually see what the user attempted to visit by checking route.params.pathMatch, which can be helpful for logging or suggesting the correct page.
<!-- NotFound.vue -->
<template>
<div>
<h1>404 - Page Not Found</h1>
<p>The path "{{ $route.params.pathMatch }}" does not exist.</p>
<RouterLink to="/">Back Home</RouterLink>
</div>
</template>
Complete Example Session
// ============================================
// PART 1: NUMERIC ID VALIDATION
// ============================================
// Only matches if ID is digits
{
path: '/product/:id(\\d+)',
name: 'ProductDetail',
component: () => import('./views/Product.vue')
}
// ============================================
// PART 2: SLUG-BASED ROUTING
// ============================================
// Matches alphanumeric slugs
{
path: '/blog/:slug([a-z0-9-]+)',
component: () => import('./views/Post.vue')
}
// ============================================
// PART 3: OPTIONAL PARAMETERS
// ============================================
// Matches /settings and /settings/privacy
{
path: '/settings/:section?',
component: () => import('./views/Settings.vue')
}
// ============================================
// PART 4: REPEATABLE SEGMENTS (Deep paths)
// ============================================
// Matches /docs/vue/router/dynamic-matching
{
path: '/docs/:path+',
component: () => import('./views/DocViewer.vue')
}
// ============================================
// PART 5: SENSITIVE & STRICT MATCHING
// ============================================
// sensitive: true makes /Order and /order different
{
path: '/order/:id',
component: Order,
sensitive: true
}
// ============================================
// PART 6: ACCESSING PARAMS IN SETUP
// ============================================
/*
const route = useRoute();
console.log(route.params.id); // "123"
*/
// ============================================
// PART 7: REACTIVE UPDATES
// ============================================
/*
watch(() => route.params.id, (id) => {
console.log('ID changed to:', id);
});
*/
// ============================================
// PART 8: NAMED NAVIGATION WITH PARAMS
// ============================================
/*
router.push({ name: 'ProductDetail', params: { id: '456' } });
*/
// ============================================
// PART 9: THE 404 FALLBACK
// ============================================
{
path: '/:pathMatch(.*)*',
component: () => import('./views/NotFound.vue')
}
// ============================================
// PART 10: COMBINING PARAMS
// ============================================
// Multiple dynamic segments in one URL
{
path: '/org/:orgId/repo/:repoName',
component: RepoView
}
The example session above covers the transition from simple numeric parameters to complex regex-validated slugs, optional sections, and the critical catch-all route for robust error handling.
Quick Reference
Dynamic Segment Syntax
| Syntax | Example | Description | Result for /p/123 |
|---|---|---|---|
:param | /p/:id | Standard dynamic segment | params.id = '123' |
:param? | /p/:id? | Optional segment | params.id = '123' (or undefined) |
:param* | /p/:path* | Zero or more segments | params.path = ['123'] |
:param+ | /p/:path+ | One or more segments | params.path = ['123'] |
Custom Regex Constraints
| Regex | Path Example | Matches | Fails |
|---|---|---|---|
(\\d+) | /:id(\\d+) | /123 | /abc |
(a|b) | /:type(a|b) | /a, /b | /c |
(.*) | /:any(.*) | Anything | (None) |
Component Access
| Environment | Method | Syntax |
|---|---|---|
| Template | Direct access | {{ $route.params.id }} |
| Options API | This context | this.$route.params.id |
| Composition API | Hook | const route = useRoute(); route.params.id |
Best Practices
✅ Do This:
// Use regex for IDs to prevent matching accidental strings
{ path: '/user/:id(\\d+)', component: UserView } // ✅
// Watch route params when reusing components
watch(() => route.params.id, loadData); // ✅
// Use names for routes with many params to simplify navigation
router.push({ name: 'user', params: { id: 1 } }); // ✅
// Always include a catch-all 404 route at the end
{ path: '/:pathMatch(.*)*', component: NotFound } // ✅
❌ Don’t Do This:
// Don't rely on onMounted for param changes in the same component
onMounted(() => { /* only runs once */ }); // ❌
// Don't use generic names like ':id' if you have multiple params
{ path: '/user/:id/post/:id' } // Shadowing error // ❌
// Don't hardcode regex logic inside component methods
// (Keep validation in the router config) // ❌
// Don't use '*' in VR4 without the pathMatch name
{ path: '*' } // Invalid in Vue Router 4 // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Param Change Ignored | Component is reused, not re-mounted | Use watch or beforeRouteUpdate |
| 404 Not Matching | Syntax is :pathMatch(.*)*, not just * | Update to Vue Router 4 syntax |
| Params are Strings | URL data is always string type | Use Number(route.params.id) if needed |
| Overlapping Routes | Two routes match the same string | Add regex to differentiate or check ranking |
| Multiple Params Missing | Using the same name for two segments | Use unique names (e.g., :userId, :postId) |
| Regex Escaping | Backslashes in strings need doubling | Use :id(\\d+) instead of :id(\d+) |
Real-World Examples
1. Numeric User ID
{ path: '/user/:id(\\d+)', component: Profile }
2. Optional Language Prefix
{ path: '/:lang(en|fr)?/home', component: Home }
3. Nested File Path
{ path: '/files/:path*', component: FileExplorer }
4. Category and Subcategory
{ path: '/shop/:cat/:sub?', component: ShopView }
5. Order Tracking (Alphanumeric)
{ path: '/track/:code([A-Z0-9]{8})', component: Tracker }
6. Route Parameter to Props
{ path: '/user/:id', component: User, props: true }
7. Named Catch-All
{ path: '/:pathMatch(.*)*', name: '404', component: NotFound }
8. Multiple Constraints
{ path: '/event/:year(\\d{4})/:month(\\d{2})', component: Event }
9. Secret Token Route
{ path: '/reset-password/:token([a-f0-9]{40})', component: Reset }
10. Navigating Programmatically
router.push({ name: 'profile', params: { username: 'john' } });
Visual
Param Capture Mechanism
┌──────────────────────────────────────────────────────────┐
│ URL: /user/123/post/hello-world │
└─────────────────────┬────────────────────────────────────┘
│
┌─────────────▼──────────────┐
│ ROUTE DEFINITION: │
│ /user/:userId/post/:slug │
└─────────────┬──────────────┘
│
┌─────────────▼──────────────┐
│ $route.params │
│ { │
│ userId: "123", │
│ slug: "hello-world" │
│ } │
└────────────────────────────┘
Regex Validation Flow
┌──────────────────────┐ ┌──────────────────────┐
│ URL: /user/abc │ │ URL: /user/123 │
└──────────┬───────────┘ └──────────┬───────────┘
│ │
┌──────▼──────┐ ┌──────▼──────┐
│ MATCHING: │ │ MATCHING: │
│ :id(\\d+) │ │ :id(\\d+) │
└──────┬──────┘ └──────┬──────┘
│ │
┌──────▼──────┐ ┌──────▼──────┐
│ REJECTED │ │ ACCEPTED │
│ (404) │ │ (Renders) │
└─────────────┘ └─────────────┘
Catch-All Resolution
┌──────────────────────────────────────────────────────────┐
│ DEFINED ROUTES: │
│ 1. /home │
│ 2. /about │
│ 3. /:pathMatch(.*)* <-- Fallback │
└───────────────────────────┬──────────────────────────────┘
│
┌───────────────▼──────────────┐
│ VISIT: /contact │
├──────────────────────────────┤
│ Check 1: No match │
│ Check 2: No match │
│ Check 3: MATCH! │
└───────────────┬──────────────┘
│
┌───────────────▼──────────────┐
│ Render NotFoundComponent │
└──────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Dynamic Prefix | : (Colon) |
| Optional Suffix | ? (Question Mark) |
| Repeatable (0+) | * (Asterisk) |
| Repeatable (1+) | + (Plus) |
| Catch-all Pattern | /:pathMatch(.*)* |
| Capture Object | $route.params |
| Hook (Comp API) | useRoute() |
| Param Type | Always string or string[] |
Key takeaways:
- Dynamic segments are reactive placeholders. They allow a single route and component to serve an infinite variety of data by capturing variable parts of the URL .
- Component reuse is the default behavior. When navigating between routes that use the same component but different parameters, Vue does not re-mount the component. You must use
watchor navigation guards to detect these changes . - Regex provides “smart” matching. By adding regular expressions to parameters, you can validate input at the routing level, ensuring that numeric IDs don’t match alphanumeric slugs .
- Quantifiers handle URL variability. Symbols like
?,*, and+allow you to define whether a segment is optional or can capture multiple parts of a path as an array . - The catch-all route is mandatory for SPAs. To prevent broken user experiences, a universal matcher like
/:pathMatch(.*)*should always be implemented to handle 404 scenarios . - Ranking supersedes order. Vue Router 4 uses a scoring system based on path specificity, meaning more detailed paths (like those with regex) are prioritized automatically over generic ones .
Remember: Dynamic routing is the bridge between your static code and your dynamic data. By combining colons, parentheses for regex, and quantifiers, you can create a robust navigation system that is both flexible enough to handle any URL structure and strict enough to prevent invalid states from reaching your components.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!