Nested Routes In Nuxt JS With Example

Lets learn how to use nexted routes in nuxt js

Nuxt.js automatically generates the vue-router configuration based on your file tree of Vue files inside the pages directory.

To navigate between pages, we recommend to use the <nuxt-link> component.
For example:
<template> <nuxt-link to="/">Home page</nuxt-link> </template>
. . .
Nested Routes
Nuxt.js lets you create nested route by using the children routes of vue-router.
To define the parent component of a nested route, you need to create a Vue file with the same name as the directory which contain your children views.

Warning: don't forget to include <nuxt-child/> inside the parent component (.vue file).

This file tree:
pages/ --| users/ -----| _id.vue -----| index.vue --| users.vue

will automatically generate:
router: { routes: [ { path: '/users', component: 'pages/users.vue', children: [ { path: '', component: 'pages/users/index.vue', name: 'users' }, { path: ':id', component: 'pages/users/_id.vue', name: 'users-id' } ] } ] }


. . .

Dynamic Nested Routes

This scenario should not often happen, but it is possible with Nuxt.js: having dynamic children inside dynamic parents.

This file tree:
pages/ --| _category/ -----| _subCategory/ --------| _id.vue --------| index.vue -----| _subCategory.vue -----| index.vue --| _category.vue --| index.vue

will automatically generate:
router: { routes: [ { path: '/', component: 'pages/index.vue', name: 'index' }, { path: '/:category', component: 'pages/_category.vue', children: [ { path: '', component: 'pages/_category/index.vue', name: 'category' }, { path: ':subCategory', component: 'pages/_category/_subCategory.vue', children: [ { path: '', component: 'pages/_category/_subCategory/index.vue', name: 'category-subCategory' }, { path: ':id', component: 'pages/_category/_subCategory/_id.vue', name: 'category-subCategory-id' } ] } ] } ] }
. . .

Unknown Dynamic Nested Routes

If you do not know the depth of your URL structure, you can use _.vue to dynamically match nested paths. This will handle requests that do not match a more specific request.

This file tree:
pages/ --| people/ -----| _id.vue -----| index.vue --| _.vue --| index.vue

Will handle requests like this:
PathFile/index.vue/people people/index.vue/people/123 people/_id.vue/ about_.vue/about/careers_.vue/ about/careers/chicago_.vue
Aditya Agrawal

Jun 13 2019

Write your response...

On a mission to build Next-Gen Community Platform for Developers