Nested routes
Nested routes render child pages inside a parent layout, matching URLs like /account/settings.
In this page:
Syntax
{
path: '/parent',
component: ParentComponent,
children: [
{ path: 'child', component: ChildComponent }
]
}
<!-- ParentComponent template -->
<router-view></router-view>
Nested routes
Add a children array to a route. The parent component contains its own router-view where the matched child appears. Child paths without a leading slash are relative to the parent. An empty child path acts as the default view.
Note:
A child path starting with / is treated as absolute, so leave it off.
Example: Nested routes
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://unpkg.com/vue-router@4/dist/vue-router.global.js"></script>
</head>
<body>
<div id="app"><router-view></router-view></div>
<script>
const Account = { template: "<section><h3>Account</h3><router-view></router-view></section>" };
const Profile = { template: "<p>Profile tab</p>" };
const Settings = { template: "<p>Settings tab</p>" };
const router = VueRouter.createRouter({
history: VueRouter.createWebHashHistory(),
routes: [{ path: "/account", component: Account, children: [
{ path: "", component: Profile },
{ path: "settings", component: Settings },
] }],
});
Vue.createApp({}).use(router).mount("#app");
router.push("/account/settings").then(async () => {
await Vue.nextTick();
console.log(document.querySelector("#app").textContent.replace(/\s+/g, " ").trim());
});
</script>
</body>
</html>
<!-- Output:
Rendered: AccountSettings tab
console: AccountSettings tab
-->
Live Example
Related Topics
Common Mistakes
- Using a leading slash on child paths
- Forgetting the nested router-view
- Expecting the parent to disappear
Chapter Summary
- children nest routes
- The parent holds a router-view
- Child paths are relative
- An empty child is the default
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: