Nested Routes and Route Parameters in Vue.js
Introduction
In this tutorial, we will learn about Nested Routes and Route Parameters in Vue.js. Vue Router is an essential part of the Vue.js ecosystem and helps us manage the routing in our applications. Vue Router allows us to map our application’s components to different paths in the URL. We can create advanced routes with parameters and even nested routes.
Nested Routes in Vue.js
Nested routes are useful when you want to create a UI with multiple nested views. They allow you to nest components within components which can be tied to different routes.
Let's understand this with an example. Consider the scenario where you have a User
component and for each user, you want to display a Profile
and Posts
component. In this case, Profile
and Posts
will be the child routes of the User
component.
First, let's define our router configuration:
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User,
children: [
{
// UserProfile will be rendered inside User's <router-view>
// when /user/:id/profile is matched
path: 'profile',
component: UserProfile
},
{
// UserPosts will be rendered inside User's <router-view>
// when /user/:id/posts is matched
path: 'posts',
component: UserPosts
}
]
}
]
})
In the User
component, make sure to include <router-view>
where child components should be rendered:
const User = {
template: `
<div class="user">
<h2>User {{ $route.params.id }}</h2>
<router-view></router-view>
</div>
`
}
Route Parameters in Vue.js
Route parameters are used when you need to create a dynamic route. For example, if you want to display user details based on their id, you would use a dynamic route that includes a route parameter.
In the router configuration, we can define a route with a parameter like this:
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User }
]
})
In this route, :id
is a route parameter. When someone navigates to /user/1
, the User
component will be displayed and 1
will be the id
parameter.
You can access route parameters in your components using this.$route.params
. For example:
const User = {
template: '<div>User {{ $route.params.id }}</div>'
}
In this component, {{ $route.params.id }}
will display the id from the route parameter.
Conclusion
In this tutorial, we have learned about Nested Routes and Route Parameters in Vue.js. Nested routes allow us to create complex UIs with multiple levels of components, each tied to a specific route. Route parameters enable us to create dynamic routes where a part of the route can change dynamically. These are powerful features of Vue.js that can be leveraged to create rich and interactive web applications. Practice using these concepts to become more proficient in Vue.js routing.