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

router-view

router-view is the placeholder where the component for the current route is rendered.

In this page:

  1. router-view
Syntax
markup
<nav>
  <router-link to="/path">link text</router-link>
</nav>
<router-view></router-view>

router-view

Place router-view where page content should appear, typically below a shared navigation. Named views let a route render several components at once. Combine with transition and keep-alive through the v-slot API to animate or cache pages.

Note: One router-view per level of nesting: nested routes need a nested router-view.

Example: router-view

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">
  <h1>My Site</h1>
  <router-view></router-view>
  <router-view name="sidebar"></router-view>
</div>
<script>
  const router = VueRouter.createRouter({
    history: VueRouter.createWebHashHistory(),
    routes: [{
      path: "/",
      components: { default: { template: "<main>Main content</main>" }, sidebar: { template: "<aside>Sidebar</aside>" } },
    }],
  });
  Vue.createApp({}).use(router).mount("#app");
  router.isReady().then(() => console.log(document.querySelector("#app").textContent.replace(/\s+/g, " ").trim()));
</script>
</body>
</html>

<!-- Output:
Rendered: My SiteMain contentSidebar
console: My SiteMain contentSidebar
-->
Live Example
Related Topics
Common Mistakes
  1. Forgetting router-view so nothing renders
  2. Using one router-view for nested routes
  3. Not handling the not-found route
Chapter Summary
  • router-view shows the matched component
  • Named views show several
  • Nested routes need nested views
  • Works with transition and keep-alive
🔒

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.