Vue Router 05 🧭 Nested Routes & Named Views — Building multi-level layouts with children and rendering multiple RouterView outlets
In a real-world Single Page Application (SPA), components are rarely flat. Most user interfaces are composed of multiple levels of nesting—a top-level “App” shell containing a “Dashboard” layout, which in turn contains a “Sidebar” and a “Content” area that changes based on sub-navigation. Mapping these visual hierarchies to the URL structure is where nested routes become indispensable. Instead of re-rendering the entire page when a user navigates from “Settings Profile” to “Settings Security,” nested routes allow the “Settings” wrapper to stay in place while only the inner content area swaps out.
Complementing this hierarchical structure is the concept of Named Views. While a standard RouterView renders a single component for a given path, complex layouts often require multiple “outlets” on the same level. For instance, a layout might have a Sidebar view, a MainContent view, and a Footer view, all of which need to change simultaneously based on the route. Named Views allow you to define these multiple outlets in your template and map specific components to them in your route configuration.
This chapter provides a deep dive into the children configuration property and the components (plural) property used for named views. We will explore how to maintain layout persistence, handle empty sub-paths for parent routes, and orchestrate complex multi-view layouts that remain perfectly synchronized with the browser’s address bar.
Key point: Nested routes allow the URL to mirror the component hierarchy using the children array and nested <RouterView> tags, while Named Views enable a single route to populate multiple <RouterView name="..."> outlets simultaneously.
Why exists
The Layout Persistence problem.
In traditional web apps, every navigation triggers a full page refresh, losing the state of your sidebar or navigation menu. Nested routes allow you to define “Layout Components” that remain mounted while their internal content is swapped. This creates a smoother, app-like experience where headers and sidebars don’t “flicker” during navigation.
The URL Hierarchy problem.
A logical URL structure like /settings/profile and /settings/security suggests a relationship. Without nested routes, you would have to define these as flat routes and manually include the “Settings Layout” in every single component. Nested routes formalize this relationship in the configuration, making the code more DRY (Don’t Repeat Yourself) and the URL structure more intuitive.
The Viewport Fragmentation problem.
Modern dashboards often have multiple distinct areas that update independently. For example, a “Mail” app might have a folder list, a message list, and a message detail view all on screen at once. Named Views allow you to treat these distinct screen regions as independent routing targets, rather than forcing a single component to manage three different sub-states.
The Component Reusability problem.
If you have a complex layout, you don’t want to wrap every page component in a “Layout” component manually. This leads to deep prop-drilling or redundant imports. By using nested routes, the parent component serves as the layout naturally, and children are “injected” into it via the router, keeping components focused on their specific data.
The “Empty Parent” problem.
When a user navigates to a parent path like /dashboard, you often want to show a “Summary” or “Home” sub-view immediately. Nested routes provide a mechanism for “default children” using empty paths, ensuring that a parent route always has meaningful content to display in its internal outlet.
The Parallel Rendering problem.
Sometimes, a specific route needs to change more than just the main content area. Maybe navigating to /admin should hide the standard footer and show a specific admin toolbar. Named Views allow you to redefine what appears in multiple outlets across the app shell for specific routes, without conditional logic in the shell itself.
a. Defining Nested Routes with children
Nested routes are defined using the children property within a route record. The children property is itself an array of route records. Crucially, a component that contains nested routes must include its own <RouterView /> to serve as the outlet for those children.
// router/index.ts
const routes = [
{
path: '/user/:id',
component: UserLayout, // This component MUST have a <RouterView />
children: [
{
// Matches /user/:id/profile
path: 'profile',
component: UserProfile
},
{
// Matches /user/:id/posts
path: 'posts',
component: UserPosts
}
]
}
];
When defining child paths, you have two choices: relative or absolute. If the child path does not start with a forward slash (/), it is appended to the parent’s path. If it does start with /, it is treated as an absolute path but still renders inside the parent’s component hierarchy.
In the UserLayout.vue component, you define where the children appear:
<!-- UserLayout.vue -->
<template>
<div class="user-layout">
<aside>User Sidebar for {{ $route.params.id }}</aside>
<main>
<!-- Sub-routes render here -->
<RouterView />
</main>
</div>
</template>
When the URL is /user/1/profile, the router renders UserLayout at the top level, and then renders UserProfile inside the UserLayout‘s <RouterView>. If the URL is just /user/1, the inner <RouterView> will be empty unless you define a default child.
b. The Default Child and Redirects
A common requirement is to display a specific child view when the user visits the parent path exactly. For example, visiting /settings should perhaps show the /settings/general view by default. There are two ways to achieve this: using an empty path or a redirect.
The Empty Path method involves adding a child with path: ''. This child will match whenever the parent path matches exactly.
{
path: '/settings',
component: SettingsLayout,
children: [
{
path: '', // Matches /settings
component: SettingsOverview
},
{
path: 'security', // Matches /settings/security
component: SettingsSecurity
}
]
}
The Redirect method is more explicit. It forces the browser’s URL to update to a specific sub-path. This is often better for SEO and clarity, as it ensures the user always sees a “clean” and specific URL.
{
path: '/settings',
component: SettingsLayout,
redirect: '/settings/general', // Redirects the user
children: [
{
path: 'general',
component: SettingsGeneral
}
]
}
Redirects can also use named routes: redirect: { name: 'settings-general' }. This is the preferred way to handle parent entries, as it prevents the UI from appearing “half-loaded” or empty.
c. Named Views: Multiple Outlets in One Route
Sometimes you don’t want a hierarchy; you want a horizontal split. Named Views allow you to have multiple <RouterView> outlets at the same level. You differentiate them using the name attribute. If no name is provided, it defaults to default.
In your template (usually App.vue or a layout component):
<template>
<div id="app">
<header><RouterView name="navigation" /></header>
<main><RouterView /></main> <!-- Default outlet -->
<footer><RouterView name="helper" /></footer>
</div>
</template>
In the router configuration, instead of the component property, you use the components (plural) property. This property takes an object where the keys match the names of the <RouterView> outlets.
const routes = [
{
path: '/',
components: {
default: HomeMain, // Goes into the unnamed <RouterView />
navigation: HomeNav, // Goes into <RouterView name="navigation" />
helper: HomeFooter // Goes into <RouterView name="helper" />
}
},
{
path: '/admin',
components: {
default: AdminMain,
navigation: AdminNav, // Sidebar-style nav instead
// helper is omitted, so that outlet remains empty
}
}
];
This is incredibly powerful for “Layout Swapping.” You can change the entire structure of the page (header, footer, sidebars) simply by changing the route, without writing complex v-if logic inside your main layout. Each route essentially “claims” the regions of the screen it wants to control.
Complete Example Session
// ============================================
// PART 1: THE DASHBOARD LAYOUT
// ============================================
// src/layouts/DashboardLayout.vue
/*
<template>
<div class="layout">
<nav><RouterView name="sidebar" /></nav>
<main><RouterView /></main>
</div>
</template>
*/
// ============================================
// PART 2: THE ROUTER CONFIG
// ============================================
import { createRouter, createWebHistory } from 'vue-router';
const routes = [
{
path: '/dashboard',
// Parent provides the structure
component: () => import('./layouts/DashboardLayout.vue'),
children: [
// PART 3: THE DEFAULT CHILD (SUMMARY)
{
path: '',
name: 'dash-main',
components: {
default: () => import('./views/Summary.vue'),
sidebar: () => import('./components/MainSidebar.vue')
}
},
// PART 4: NESTED VIEW WITH ALTERNATE SIDEBAR
{
path: 'reports',
name: 'dash-reports',
components: {
default: () => import('./views/Reports.vue'),
sidebar: () => import('./components/ReportsSidebar.vue')
}
},
// PART 5: ABSOLUTE PATH NESTED (Matches /settings)
{
path: '/settings',
component: () => import('./views/Settings.vue')
}
]
},
// PART 6: MULTI-VIEW HOME PAGE
{
path: '/',
components: {
default: () => import('./views/Home.vue'),
sidebar: () => import('./components/Empty.vue')
}
}
];
// ============================================
// PART 7: PROGRAMMATIC NESTED NAVIGATION
// ============================================
// router.push('/dashboard/reports')
// ============================================
// PART 8: NAMED NAVIGATION TO CHILD
// ============================================
// router.push({ name: 'dash-reports' })
// ============================================
// PART 9: PROPS IN NESTED ROUTES
// ============================================
// { path: 'user/:id', component: User, props: true }
// ============================================
// PART 10: MOUNTING
// ============================================
const router = createRouter({
history: createWebHistory(),
routes
});
The parts above build a complex Dashboard system where the sidebar changes depending on whether the user is looking at General Summary or specific Reports, all while utilizing a shared layout component.
Quick Reference
Nested Route Options
| Property | Type | Description |
|---|---|---|
children | Array | Nested route records |
path: '' | String | Matches the parent URL exactly |
path: 'rel' | String | Matches parent/rel |
path: '/abs' | String | Matches /abs but renders in parent |
Named View Syntax
| Context | Syntax |
|---|---|
| Template | <RouterView name="sidebar" /> |
| Default | <RouterView /> (implies name=”default”) |
| Route Config | components: { default: A, sidebar: B } |
| Usage | Swapping multiple UI areas at once |
Common Layout Patterns
| Pattern | Technique |
|---|---|
| persistent Sidebar | Parent contains Sidebar + RouterView |
| Dynamic Sidebar | Parent contains RouterView name="sidebar" |
| Full Page Swap | No nesting, completely different top-level route |
Best Practices
✅ Do This:
// Use relative paths (no slash) for children to maintain hierarchy
path: 'profile' // ✅
// Always provide a default child or redirect for parent routes
path: '', component: Overview // ✅
// Use Named Views for things that aren't strictly content (e.g. Nav)
components: { default: Page, nav: Navbar } // ✅
// Keep the parent layout component slim
// It should only handle layout, not business logic // ✅
❌ Don’t Do This:
// Don't forget the <RouterView /> in the parent component
// (Children will never render!) // ❌
// Don't start child paths with '/' unless you intend to
// (It overrides the path hierarchy but not the UI hierarchy) // ❌
// Don't use 'component' when using 'components' (named views)
component: MyView, components: { ... } // ❌
// Don't deeply nest routes (more than 3 levels)
// (Makes URL management and state tracking very difficult) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Child not rendering | Missing <RouterView /> in parent component | Add outlet to parent template |
| URL mismatch | Used /child (absolute) instead of child | Remove leading slash for relative nesting |
| Empty parent page | Parent path matched but no path: '' defined | Add a default child or a redirect |
| Components not found | Used component instead of components | Change to plural for named views |
| Path collision | Child path name same as another top-level path | Ensure unique naming or relative nesting |
| Props missing in child | Forgot props: true in child route record | Add props: true to the specific child record |
Real-World Examples
1. Standard Dashboard Layout
{ path: '/dash', component: DashLayout, children: [{ path: 'stats', component: Stats }] }
2. Default Redirect
{ path: '/admin', redirect: '/admin/users', children: [...] }
3. Sidebar + Main Named Views
components: { default: MainArea, sidebar: LeftMenu }
4. Shared Settings Shell
{ path: '/settings', component: SettingsShell, children: [{ path: 'profile', component: Profile }] }
5. Mobile vs Desktop Views
components: { default: isMobile ? MobView : DeskView }
6. Multi-Nested Breadcrumbs
{ path: 'a', children: [{ path: 'b', children: [{ path: 'c', component: C }] }] }
7. Absolute Path in Nested UI
{ path: '/dashboard', component: Dash, children: [{ path: '/login', component: Login }] }
8. Named View for Modal
components: { default: Page, modal: UserModal }
9. No-Layout Public Pages
{ path: '/login', component: SimpleLogin } // No children/nesting
10. Admin Toolbar Toggle
{ path: '/admin', components: { default: AdminPage, top: AdminBar } }
Visual
Nested Route Architecture
┌──────────────────────────────────────────────────────────┐
│ App.vue (Top-level RouterView) │
│ ┌────────────────────────────────────────────────────┐ │
│ │ DashboardLayout.vue │ │
│ │ ┌──────────────┐ ┌─────────────────────────────┐ │ │
│ │ │ Sidebar │ │ Internal RouterView │ │ │
│ │ │ (Persistent) │ │ ┌───────────────────────┐ │ │ │
│ │ │ │ │ │ Child Component │ │ │ │
│ │ │ │ │ │ (Stats/Settings) │ │ │ │
│ │ └──────────────┘ └─────────────────────────────┘ │ │
│ └────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────┘
Named Views Map
┌──────────────────────────────────────────────────────────┐
│ LAYOUT TEMPLATE │
│ <header> <RouterView name="nav" /> </header> │
│ <aside> <RouterView name="sidebar" /> </aside> │
│ <main> <RouterView /> </main> │
└──────────────────────────┬───────────────────────────────┘
│
┌─────────────▼──────────────┐
│ ROUTE DEFINITION │
│ components: { │
│ nav: GlobalHeader, │
│ sidebar: UserMenu, │
│ default: ProfileContent │
│ } │
└────────────────────────────┘
Relative vs. Absolute Children
┌──────────────────────────────────────────────────────────┐
│ PATH: /parent │
│ COMPONENT: ParentComp │
├──────────────────────────────────────────────────────────┤
│ CHILD A: path: 'child' => Matches /parent/child │
│ CHILD B: path: '/other' => Matches /other │
│ │
│ *BOTH render inside ParentComp's <RouterView> │
└──────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Hierarchy Prop | children |
| Relative Path | path: 'profile' (No leading /) |
| Absolute Path | path: '/profile' (Leading /) |
| Named View Tag | <RouterView name="x" /> |
| Multi-Component Prop | components: { ... } |
| Default Child | path: '' |
| Persistent UI | Handled by Parent component |
| Outlet Requirement | Must have <RouterView /> |
Key takeaways:
- Nested routes mirror UI hierarchy. By using the
childrenarray, you can ensure that the URL structure reflects the nesting of your components, allowing for persistent layouts . - Relative paths append, absolute paths replace. Use
path: 'sub'to create/parent/sub, but usepath: '/sub'if you want the child to render inside the parent layout but have a top-level URL . - Every parent needs an outlet. If you define children for a route, that route’s component must contain a
<RouterView />or the children will never be rendered . - Named views solve multi-region layouts. Use
components(plural) and<RouterView name="...">when a single route needs to populate multiple areas of the screen (like a sidebar and a main area) simultaneously . - Parent routes need a “Landing” state. Use an empty path (
path: '') or aredirectto ensure that when a user visits the parent URL, they aren’t greeted with an empty content area . - Layouts stay mounted during sub-navigation. Because the parent component remains active while children are swapped, you can maintain scroll positions, animations, and local state in sidebars .
Remember: Nested routes and Named views are the architects of your application’s layout. Use nesting to build logical hierarchies where parent layouts wrap child content, and use named views to manage complex grids where multiple regions of the screen need to react to navigation independently.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!