← Back to Vue.js Course | Chapter 7: Vue Router | Lesson 6 of 7

Nested routes

Nested routes render child pages inside a parent layout, matching URLs like /account/settings.

In this page:

  1. Nested routes
Syntax
markup
{
  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

markup
<!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
  1. Using a leading slash on child paths
  2. Forgetting the nested router-view
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.