How to Use Vue Router's router-view Component

Oct 20, 2021

Vue Router's <router-view> component displays the component or template that corresponds to the current URL.

<script src="https://unpkg.com/vue@3"></script>
<script src="https://unpkg.com/vue-router@4"></script>

<div id="app">
  <div>
    <router-link to="/home">Go to Home</router-link> <br />
    <router-link to="/about">Go to About</router-link>
  </div>
  <h1>Observe the Change Below!</h1>
  <router-view></router-view>
</div>
<script>
  const routes = [
    { path: '/home', component: { template: '<div>Home</div>' } },
    { path: '/about', component: { template: '<div>About</div>' } }
  ];
  const router = VueRouter.createRouter({
    history: VueRouter.createWebHashHistory(),
    routes,
  });
  const app = Vue.createApp({});
  app.use(router);
  app.mount('#app');
</script>

Below is a live example:

Go to Home
Go to About

Observe the Change Below!

Props

Note that router-view only takes one prop, name. You cannot use router-view to pass props to the rendered component, you need to use the props option for routes.

const router = VueRouter.createRouter({
  {
    path: '/user/:id',
    component: app.component('user'),
    // Pass the `id` route parameter as the `userId` prop.
    props: (route) => {
      return {
        userId: route.params.id
      };
    }
  }
});

Vue School has some of our favorite Vue video courses. Their Vue.js Master Class walks you through building a real world application, and does a great job of teaching you how to integrate Vue with Firebase. Check it out!


More Vue Tutorials