How to Use router-view in Vue: Simple Guide with Examples
In Vue,
<router-view> is a placeholder component where matched route components render. You use it inside your main layout or parent component to show the content of the current route automatically.Syntax
The <router-view> component is used in your Vue template to mark where the matched route's component should appear. It does not need any props for basic usage but can accept name for named views.
- <router-view>: Default outlet for route components.
- name (optional): Used to specify named views when multiple views are rendered.
vue
<router-view></router-view>
Output
Displays the component matched by the current route inside this placeholder.
Example
This example shows a simple Vue app with two routes: Home and About. The <router-view> in App.vue renders the matched component based on the URL.
vue
import { createApp } from 'vue'; import { createRouter, createWebHistory } from 'vue-router'; const Home = { template: '<div><h2>Home Page</h2><p>Welcome to the home page.</p></div>' }; const About = { template: '<div><h2>About Page</h2><p>Learn more about us here.</p></div>' }; const routes = [ { path: '/', component: Home }, { path: '/about', component: About } ]; const router = createRouter({ history: createWebHistory(), routes }); const App = { template: ` <div> <nav> <router-link to="/">Home</router-link> | <router-link to="/about">About</router-link> </nav> <router-view></router-view> </div> ` }; createApp(App).use(router).mount('#app');
Output
<nav>Home | About</nav>
<h2>Home Page</h2>
<p>Welcome to the home page.</p>
Common Pitfalls
1. Forgetting to include <router-view> in your main component: Without it, no route components will show.
2. Using plain <a> tags without Vue Router navigation: This causes full page reloads instead of smooth route changes.
3. Not setting up the router properly with createRouter and createWebHistory: This breaks routing functionality.
vue
/* Wrong: No router-view, so no route content shown */ const AppWrong = { template: `<div><nav>...</nav></div>` }; /* Right: Include router-view to display route components */ const AppRight = { template: `<div><nav>...</nav><router-view></router-view></div>` };
Quick Reference
- <router-view>: Place where matched route component renders.
- Use
nameattribute for named views. - Always include
<router-view>in your layout to see route content. - Use Vue Router's
router-linkor programmatic navigation to avoid page reloads.
Key Takeaways
Use
<router-view> as a placeholder to render matched route components.Always include
<router-view> in your main or parent component to display routed content.Use Vue Router's navigation methods to change routes without reloading the page.
Named views require
name attributes on <router-view> and route definitions.Without
<router-view>, route components will not appear in your app.