Nested routes let you show pages inside other pages. This helps organize your app and keep related views together.
0
0
Nested routes and child views in Vue
Introduction
You want a main page with smaller sections inside it, like a dashboard with tabs.
You have a profile page with subpages for settings, posts, and friends.
You want to keep your URL structure clear and show parts of the page that change inside a main layout.
You want to reuse a layout component and show different content inside it based on the route.
Syntax
Vue
const routes = [ { path: '/parent', component: ParentComponent, children: [ { path: 'child', component: ChildComponent } ] } ];
The children array holds nested routes inside a parent route.
Child paths do not start with a slash; they are relative to the parent path.
Examples
This example shows a dashboard with two child views: stats and settings.
Vue
const routes = [ { path: '/dashboard', component: Dashboard, children: [ { path: 'stats', component: Stats }, { path: 'settings', component: Settings } ] } ];
An empty string
'' as a child path means it shows by default when visiting the parent route.Vue
const routes = [ { path: '/profile', component: Profile, children: [ { path: '', component: ProfileOverview }, { path: 'posts', component: ProfilePosts } ] } ];
Sample Program
This Vue app shows a parent view with a nested child view. When you visit /parent/child, you see the child content inside the parent layout.
Vue
<template> <router-view /> </template> <script setup> import { createRouter, createWebHistory } from 'vue-router'; import { createApp } from 'vue'; const Parent = { template: `<div> <h2>Parent View</h2> <router-view /> </div>` }; const Child = { template: `<div><p>This is the child view inside the parent.</p></div>` }; const routes = [ { path: '/parent', component: Parent, children: [ { path: 'child', component: Child } ] } ]; const router = createRouter({ history: createWebHistory(), routes }); const app = createApp({}); app.use(router); app.mount('#app'); </script>
OutputSuccess
Important Notes
Always include a <router-view /> in the parent component to show child views.
Child routes build on the parent path automatically, so no leading slash in child paths.
Use nested routes to keep your app organized and improve user experience with clear layouts.
Summary
Nested routes let you show smaller views inside bigger views.
Child routes go inside a children array in the parent route.
Use <router-view /> in parent components to display child views.