Nested Routes is one of the most wonderful feature which provided by Vue.
In this article, I will cover how we use nested routes in appropriate places. But before we begin, I'm assuming that you have Vue.js and Vue Router installed in your local machine and already have basic understanding of both. if so, then it's time to dive deeper into this topic!
How do Nested Routes work?
Okay, first of all let's say we have a page that displays an unordered list of Elf.
When one of those link is clicked, we want to show the details. How do we do this? Well, there is two approach we can use. First by using the one called children
and the second one is without children
options.
Sometimes, all of this approach make it difficult for new learners. The biggest mistake of developer is to assume they both have the same functionality. In fact, they are something different...
Nested With Children
With this options, your code will look like the one below. Look, path of :elfName
are inside the path of '/elf-list
. This will make the elf-list
become a parent of the :elfName
.
const routes = [
{
path: "/elf-list",
component: () => import("./pages/Elf.vue"),
children: [
{
path: ":elfName",
component: () => import("./components/ElfDetails.vue"),
},
],
},
];
While using this approach, all of those components still in one page.
As you can see in the picture below, even if the url changes, children
options make old element stay in their position. The children element are always with their parents and inseparable.
Actually, this depending on where you put the <router-view>
tag. In my case, the <router-view>
is above the elf-list
component.
If you put the <router-view>
below the elf-list
component on your code, the children element also will displayed in the below of the parent element.
Nested Without Children
This is a little different from the previous approach. We don't use children
options. Instead, we make the :elfName
separate from the /elf-list
path.
If you notice, that ./components/ElfDetails.vue
has changed to ./pages/ElfDetails.vue
. This is just to indicate that the children elements are separate from parent elements and they are on different pages.
const routes = [
{
path: "/elf-list",
component: () => import("./pages/Elf.vue"),
},
{
path: "/elf-list/:elfName",
component: () => import("./pages/ElfDetails.vue"),
},
];
With this approach, we can see when one of those link is clicked, the old element suddenly disappear and the new element came.
It means whenever the route are separate from each other, the page will become separate too. That is the key!
Conclusion
Maybe you wondering when we should using one of them. Of course it's depending on your purpose.
If you want to show a modal box or a search bar that stay in one page, then thechildren
options will be the right choice!