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>.