router-view
router-view is the placeholder where the component for the current route is rendered.
In this page:
Syntax
<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
<!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
- Forgetting router-view so nothing renders
- Using one router-view for nested routes
- 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: