Vue3 Fundamentals ยท Vue Router

Routes and RouterView

Routes and `<RouterView>`

Routes and RouterView

A single-page app still has URLs. Vue Router is the official library that maps each URL to a component, so / shows the home page and /about shows the about page without a full reload.

Vue Router is a separate package, so you install it and register it as a plugin:

import { createRouter, createWebHistory } from 'vue-router';

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About },
  ],
});

app.use(router);

Each entry in routes pairs a path with the component to render. The history option decides how the URL is tracked; createWebHistory() uses the browser's History API for clean URLs.

Once the plugin is registered, two components do the work in your template. <RouterLink to="/about"> renders an anchor and navigates on click, and <RouterView /> is the placeholder where the matched component appears. In <FileName /> you place <RouterView /> once, and every route renders into it:

<template>
  <nav>
    <RouterLink to="/">Home</RouterLink>
    <RouterLink to="/about">About</RouterLink>
  </nav>
  <RouterView />
</template>

The URL decides which component fills <RouterView />. You declare the map once; the router swaps the view as the URL changes.

You are about to answer a short quiz on routes and <RouterView>.

  1. Vue Router maps each URL path to a component, so the view swaps without a full page reload.
  2. A route is declared with a `path` and the ___ to render.
  3. `<RouterView />` is the placeholder where the matched route's component renders.
  4. `<RouterLink to="/about">` renders an anchor and navigates on ___.
  5. `createWebHistory()` uses the browser's History API to produce clean URLs.
  6. You must place `<RouterView />` in every route's component.