Introduction to Dynamic Routing and Route Parameters
Dynamic routing in Vue.js allows you to create routes that are based on parameters, making your application more flexible and versatile. Route parameters enable you to pass data to your components and create dynamic, data-driven views. In this guide, we'll explore how to set up dynamic routes with route parameters in Vue.js and utilize them in your Vue components.
Defining Dynamic Routes with Route Parameters
In your Vue Router configuration, you can define dynamic routes with route parameters. Route parameters are indicated by a colon followed by the parameter name. Here's an example of defining a dynamic route with a parameter for a user profile:
// In your router configuration
const router = new VueRouter({
routes: [
{
path: '/user/:id',
component: UserProfile,
},
],
});
In this example, we've defined a dynamic route that accepts a parameter named id
in the path. This parameter can be used to load user profiles dynamically.
Accessing Route Parameters in a Component
You can access route parameters in your Vue components using the $route
object. Here's an example of accessing route parameters in a component:
<template>
<div>
<h2>User Profile</h2>
<p>User ID: {{ $route.params.id }}</p>
</div>
</template>
<script>
export default {
// Component logic here
};
</script>
In this example, we've accessed the id
route parameter using $route.params.id
and displayed it in the component template.
Navigating to Dynamic Routes with Route Parameters
You can navigate to dynamic routes with route parameters using the router-link
component or the $router.push
method. Here's an example using router-link
:
<template>
<div>
<router-link :to="'/user/' + userId">View User Profile</router-link>
</div>
</template>
<script>
export default {
data() {
return {
userId: 123, // Replace with the desired user ID
};
},
};
</script>
In this example, we've used router-link
to create a link to a user's profile based on the userId
data property.
Conclusion
Vue.js dynamic routing with route parameters provides a powerful mechanism for creating flexible and data-driven views in your application. By defining dynamic routes and accessing route parameters, you can build dynamic and personalized user experiences in your Vue.js application.