TExcelTAD
Home › Vue › Vue Routing

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):

bash
npm install vue-router@4

Define routes — each one maps a path to a component — and create the router:

js
// 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
  ]
})
js
// 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:

vue
<!-- 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
js
// 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.

html · try it yourself
<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.

html · try it yourself
<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 + '
  

));
      if (m) {
        const params = Object.fromEntries(names.map((n, i) => [n, m[i + 1]]));
        return { component: r.component, params };
      }
    }
    return { component: NotFound, params: {} };
  }

  createApp({
    setup() {
      const stack = ref(['/']);
      const path = computed(() => stack.value[stack.value.length - 1]);
      const match = computed(() => matchRoute(path.value));
      const push = (p) => { if (p !== path.value) stack.value.push(p); };
      const back = () => { if (stack.value.length > 1) stack.value.pop(); };
      return { stack, path, match, push, back };
    }
  }).mount('#app');
</script>

This is roughly what Vue Router does — plus nested routes, guards, scroll handling, lazy loading and real URL syncing.

Syncing with the URL hash

In a real page you'd store the path in the address bar so it survives reloads and works with Back/Forward. With hash mode that's just location.hash and the hashchange event (not runnable in these sandboxed frames, which can't change their own URL safely):

js
const currentPath = ref(location.hash.slice(1) || '/')
window.addEventListener('hashchange', () => {
  currentPath.value = location.hash.slice(1) || '/'
})
// links: <a href="#/about">About</a>  — the browser updates the hash, the listener updates the ref

Tip: Use createWebHashHistory() when deploying to a static host without rewrite rules (like GitHub Pages). For clean URLs with createWebHistory(), the server must answer every path with index.html.

Test yourself

Which component renders the component of the current route in Vue Router?

  1. <RouterLink>
  2. <RouterView>
  3. <RoutePage>
  4. <component :is>

For the route /products/:id, what is route.params.id at /products/42?

  1. 42 (number)
  2. '42' (string)
  3. ':id'
  4. undefined

Which history mode works on any static host without server configuration?

  1. createWebHistory()
  2. createMemoryHistory()
  3. createWebHashHistory()
  4. createServerHistory()