Vue Routing
A single-page application (SPA) loads one HTML page and then swaps views with JavaScript instead of loading new pages from the server. To make that feel like a normal website — with addresses like /products/42, working Back/Forward buttons and shareable links — you need a router: something that maps the URL to the component to show.
Vue's official router is Vue Router. This lesson explains its main concepts, then you'll build a tiny router yourself to see how it works inside.
Vue Router in a project
Install it (or tick "Router" in npm create vue@latest):
npm install vue-router@4Define routes — each one maps a path to a component — and create the router:
// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
export default createRouter({
history: createWebHistory(),
routes: [
{ path: '/', name: 'home', component: HomeView },
{ path: '/about', name: 'about', component: () => import('../views/AboutView.vue') }, // lazy-loaded
{ path: '/users/:id', name: 'user', component: () => import('../views/UserView.vue') },
{ path: '/:pathMatch(.*)*', component: () => import('../views/NotFound.vue') } // 404
]
})// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')In the root component, <RouterLink> renders navigation links and <RouterView> is the place where the matched component appears:
<!-- App.vue -->
<template>
<nav>
<RouterLink to="/">Home</RouterLink>
<RouterLink to="/about">About</RouterLink>
<RouterLink :to="{ name: 'user', params: { id: 7 } }">User 7</RouterLink>
</nav>
<RouterView />
</template>Key concepts
| Concept | What it is |
|---|---|
routes |
Array of { path, component } records |
<RouterView> |
Placeholder that renders the component of the current route |
<RouterLink to="…"> |
A link that navigates without reloading; gets an router-link-active class when active |
Dynamic segment :id |
Part of the path captured as a param: /users/7 → route.params.id === '7' |
useRoute() |
The current route (path, params, query) inside <script setup> |
useRouter() |
The router instance: router.push('/about'), router.back() |
| History mode | createWebHistory() → clean URLs (/about, needs server config); createWebHashHistory() → /#/about (works on any static host) |
| Navigation guards | router.beforeEach((to, from) => …) — e.g. redirect to login |
| Nested routes | children: […] + a <RouterView> inside the parent view |
// reading params and navigating in a component
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
console.log(route.params.id, route.query.tab)
router.push({ name: 'home' })
// a global guard
router.beforeEach((to) => {
if (to.meta.requiresAuth && !isLoggedIn()) return { path: '/login', query: { redirect: to.fullPath } }
})Build a mini router: step 1
The core idea is small: keep the current path in a reactive ref, map it to a component, and render it with <component :is>. Navigation just changes the ref.
<style>
nav button { background: none; border: none; color: #42b883; text-decoration: underline; cursor: pointer; font-size: 15px; }
nav button.active { font-weight: bold; color: #1f2937; text-decoration: none; }
.view { border: 1px solid #ddd; padding: 10px; margin-top: 6px; }
</style>
<div id="app">
<nav>
<button v-for="(comp, path) in routes" :key="path" :class="{ active: path === currentPath }" @click="go(path)">
{{ path }}
</button>
</nav>
<div class="view">
<component :is="currentView"></component>
</div>
<small>Current path: {{ currentPath }}</small>
</div>
<script type="module">
import { createApp, ref, computed } from 'vue';
const HomeView = { template: `<h3>🏠 Home</h3><p>Welcome to the shop.</p>` };
const AboutView = { template: `<h3>ℹ️ About</h3><p>We sell tea since 1999.</p>` };
const NotFound = { template: `<h3>404</h3><p>Page not found.</p>` };
createApp({
setup() {
const routes = { '/': HomeView, '/about': AboutView, '/missing': null };
const currentPath = ref('/');
const currentView = computed(() => routes[currentPath.value] || NotFound);
const go = (path) => { currentPath.value = path; console.log('navigated to', path); };
return { routes, currentPath, currentView, go };
}
}).mount('#app');
</script>Step 2: dynamic params and a history stack
A real router also matches patterns like /users/:id and remembers where you came from. Here a small matchRoute() turns route patterns into regular expressions, passes params as props, and keeps a history array for a Back button.
<style>
.link { background: none; border: none; color: #42b883; text-decoration: underline; cursor: pointer; padding: 0 4px; }
.view { border: 1px solid #ddd; padding: 10px; margin: 6px 0; }
</style>
<div id="app">
<nav>
<button class="link" @click="push('/')">Home</button>
<button class="link" @click="push('/users')">Users</button>
<button class="link" @click="push('/users/2')">User 2</button>
<button class="link" @click="push('/nope')">Broken link</button>
| <button @click="back" :disabled="stack.length < 2">◀ Back</button>
</nav>
<div class="view">
<component :is="match.component" v-bind="match.params" @navigate="push"></component>
</div>
<small>URL: {{ path }} · params: {{ JSON.stringify(match.params) }}</small>
</div>
<script type="module">
import { createApp, ref, computed } from 'vue';
const users = { 1: 'Ana', 2: 'Bao', 3: 'Chi' };
const routes = [
{ path: '/', component: { emits: ['navigate'], template: `<h3>Home</h3>` } },
{ path: '/users', component: {
emits: ['navigate'],
setup: () => ({ users }),
template: `<h3>Users</h3>
<button v-for="(name, id) in users" :key="id" class="link" @click="$emit('navigate', '/users/' + id)">{{ name }}</button>`
} },
{ path: '/users/:id', component: {
props: ['id'],
emits: ['navigate'],
setup: () => ({ users }),
template: `<h3>User #{{ id }}</h3><p>Name: {{ users[id] || 'unknown' }}</p>`
} }
];
const NotFound = { emits: ['navigate'], template: `<h3>404 — no route matches</h3>` };
function matchRoute(path) {
for (const r of routes) {
const names = [];
const pattern = r.path.replace(/:(\w+)/g, (_, name) => { names.push(name); return '([^/]+)'; });
const m = path.match(new RegExp('^' + pattern + '