Vue Router: Dynamic Routes
Dynamic routes in Vue Router allow you to create routes that match a variable URL segment. This is incredibly useful for displaying details of individual resources, like blog posts, user profiles, or product pages. Instead of defining a route for every possible resource, you define a pattern that matches a range of URLs.
1. Defining Dynamic Segments
Dynamic segments are defined using a colon (:) before the segment name in your route path.
const routes = [
{
path: '/user/:id',
component: UserProfile
},
{
path: '/post/:slug',
component: BlogPost
}
];
/user/:id: This route will match URLs like/user/1,/user/2,/user/some-user-id.idis the name of the dynamic segment./post/:slug: This route will match URLs like/post/my-first-post,/post/another-post.slugis the name of the dynamic segment.
2. Accessing Route Parameters
Within your component, you can access the value of the dynamic segment using the $route.params object.
<template>
<div>
<h1>User Profile</h1>
<p>User ID: {{ userId }}</p>
</div>
</template>
<script>
export default {
computed: {
userId() {
return this.$route.params.id;
}
},
mounted() {
// You can also access the parameter in the mounted lifecycle hook
console.log("User ID:", this.$route.params.id);
}
};
</script>
In this example:
this.$route.params.idretrieves the value of theidsegment from the URL.- The
userIdcomputed property makes the ID easily accessible in the template.
3. Regular Expression Constraints (Route Meta Fields)
You can add regular expression constraints to dynamic segments to ensure they match a specific pattern. This is done using the meta field within the route definition.
const routes = [
{
path: '/post/:slug',
component: BlogPost,
meta: {
regex: /^[a-z0-9-]+$/ // Only allow lowercase letters, numbers, and hyphens
}
}
];
Important: You'll need to add a navigation guard to check the regex before rendering the component.
router.beforeEach((to, from, next) => {
if (to.meta && to.meta.regex) {
const regex = new RegExp(to.meta.regex);
if (regex.test(to.params[Object.keys(to.params)[0]])) { // Get the first param name
next();
} else {
next('/404'); // Redirect to a 404 page or handle the error
}
} else {
next();
}
});
This code:
- Checks if the route has a
regexmeta field. - Creates a regular expression object from the
regexstring. - Tests the value of the dynamic segment (the first parameter in
to.params) against the regular expression. - If the test fails, it redirects to a 404 page. Otherwise, it proceeds to the next route guard or renders the component.
4. Multiple Dynamic Segments
You can have multiple dynamic segments in a single route.
const routes = [
{
path: '/category/:categoryName/post/:postId',
component: PostDetails
}
];
This route will match URLs like:
/category/programming/post/123/category/javascript/post/456
You can access the segments using:
this.$route.params.categoryName
this.$route.params.postId
5. Optional Dynamic Segments
You can make a dynamic segment optional by adding a question mark (?) after it.
const routes = [
{
path: '/user/:id?',
component: UserProfile
}
];
This route will match both /user/123 and /user. When the segment is missing, the corresponding parameter in $route.params will be undefined. You'll need to handle this case in your component.
6. Using path with Regular Expressions Directly (Vue Router 4+)
Vue Router 4 introduced a more direct way to define routes with regular expressions in the path itself.
const routes = [
{
path: '/post/[a-z0-9-]+', // Matches slugs with lowercase letters, numbers, and hyphens
component: BlogPost
}
];
This simplifies the process compared to using meta and navigation guards. The square brackets [] denote the dynamic segment with the regex. This approach is generally preferred in Vue Router 4 and later.
Best Practices
- Clear Naming: Use descriptive names for your dynamic segments (e.g.,
postId,slug,userId). - Validation: Always validate the values of dynamic segments to prevent errors and security vulnerabilities. Regular expressions are a powerful tool for validation.
- Error Handling: Provide a good user experience when a dynamic segment doesn't match the expected pattern (e.g., redirect to a 404 page).
- Consider Route Parameters for Filtering/Sorting: Dynamic segments are often used to pass IDs, but can also be used for filtering or sorting data.