By the end of the components module, Colmena Bookings had a problem that no prop or slot can solve: everything lives on a single page. The catalogue, the room details and the form are all shown at once, no screen has an address of its own, reloading returns everything to its initial state and the browser's Back button takes the user out of the application. In this lesson you will understand what "routing" means in a single-page application (SPA), which browser mechanisms make it possible without reloading, which problems Vue Router, Vue's official router, solves and what its fundamental pieces are. You will install it in Colmena, write a minimal self-contained example to see all the pieces working together and draw the map of screens that we will build during the rest of the module.

Contents

  1. Multi-page websites versus single-page applications
  2. How the URL changes without reloading the page
  3. What Vue Router solves
  4. The history modes
  5. The fundamental pieces
  6. Installing it in Colmena Bookings
  7. A minimal example, line by line
  8. Colmena's map of screens

  1. Multi-page websites versus single-page applications

1.1 The classic multi-page website

In a traditional website (an MPA, Multi-Page Application), each address corresponds to a different HTML document that the server generates. When the user clicks a link, the browser discards the current page, requests the new one from the server and renders it from scratch: it downloads the CSS and JavaScript again (or reads them from the cache), runs the scripts again and loses all the state held in memory.

sequenceDiagram
    participant U as User
    participant B as Browser
    participant S as Server
    U->>B: Clicks the "Rooms" link
    B->>S: GET /rooms
    S-->>B: Full HTML for /rooms
    Note over B: Discards the previous page,<br/>parses the HTML, loads CSS and JS,<br/>runs the scripts again
    B-->>U: Renders the rooms page
    U->>B: Clicks "Back"
    B->>S: GET /home (or reads it from the cache)
    S-->>B: Full HTML for /home
    B-->>U: Renders the home page from scratch

Advantages: it is simple, each URL works on its own and the browser history works without any effort. Disadvantages: every navigation involves a flicker and a wait, and state cannot be kept between screens without storing it on the server, in cookies or in the browser's storage.

1.2 The single-page application

In an SPA (Single-Page Application), like the one Vite generates, the server delivers a single index.html with the application's JavaScript. From then on, it is the JavaScript itself that decides what to render. When an internal link is clicked, the application intercepts the click, changes the URL in the address bar and replaces the components on the screen, without requesting any new document from the server. Only data (the API calls) and, if they are loaded on demand, the code chunks for each screen travel over the network.

sequenceDiagram
    participant U as User
    participant B as Browser
    participant R as Router (JavaScript)
    participant S as Server
    U->>B: Opens colmena.example/
    B->>S: GET /
    S-->>B: index.html + the application's JS
    B-->>U: Renders the home screen
    U->>R: Clicks the "Rooms" link
    R->>B: history.pushState(…, '/rooms')
    Note over B: The URL changes,<br/>but there is NO document request
    R-->>U: Replaces the home component with the rooms one
    R->>S: (optional) GET /api/rooms: data only
    U->>B: Clicks "Back"
    B->>R: popstate event (URL = /)
    R-->>U: Renders the home component again
Aspect Multi-page website (MPA) Single-page application (SPA)
Who decides what is rendered The server, for each URL The client's JavaScript
When navigating A new document is downloaded and parsed Components are swapped; the page does not reload
In-memory state Lost on every navigation Kept between screens
First load Fast (just that page) Heavier (the whole application), unless the code is split
Subsequent navigations Slower, with a flicker Instant
History and URL Work on their own Have to be managed (that is the router's job)
SEO Natural: the HTML arrives with the content Requires care or server-side rendering (09-06)

The key row is the second to last: in an SPA, giving each screen its own URL, making the Back button work and having a shared link open the right screen does not happen on its own. It is the router's job.

  1. How the URL changes without reloading the page

2.1 The History API

Browsers offer the History API (window.history), which lets you manipulate the tab's history from JavaScript:

Method or event What it does Does it reload?
history.pushState(state, '', url) Adds a new entry to the history and changes the visible URL No
history.replaceState(state, '', url) Replaces the current entry (you cannot "go back" to the previous one) No
history.back() / forward() / go(n) Moves through the history, like the browser's buttons No, if the entries belong to the same SPA
popstate event Fired on window when the user (or back/go) moves through the history —

You can try it right now in the console of any page (for example, Colmena's, with npm run dev):

// 1. Change the URL without reloading: the address bar shows /rooms
history.pushState({ screen: 'rooms' }, '', '/rooms')

// 2. Listen for movements through the history
window.addEventListener('popstate', (event) => {
  console.log('We are now at', location.pathname, 'with state', event.state)
})

// 3. Click the browser's Back button:
//    → "We are now at / with state null"
  • pushState receives a state object (it is stored with the history entry and retrieved in popstate), a title that browsers ignore (which is why '' is passed) and the new URL, which must be of the same origin.
  • pushState does not fire popstate and does not render anything: it only changes the URL. Whoever calls pushState must also update the screen.
  • popstate lets you know when the user clicks Back or Forward. At that point the application must read location.pathname and render the corresponding screen.

With these two pieces you can build a router by hand: intercept clicks on internal links (event.preventDefault() + pushState + render) and react to popstate (render). That is exactly what Vue Router does under the hood, plus everything we will see in section 3.

2.2 Hash mode

Before the History API existed, another trick was used: the part of the URL after the # (the fragment or hash) is never sent to the server, and changing it does not reload the page. So https://colmena.example/#/rooms and https://colmena.example/#/dashboard both request the same document (/) from the server, and it is the JavaScript that reads the fragment:

// Change "screen" in hash mode
location.hash = '#/rooms'

// React to changes (also with Back/Forward)
window.addEventListener('hashchange', () => {
  console.log('Current screen:', location.hash.slice(1)) // '/rooms'
})

Its great advantage is that it needs no configuration on the server. Its drawbacks are that the URLs are less clean and that the fragment is no longer available for its natural use (jumping to an anchor on the page).

  1. What Vue Router solves

Vue Router is Vue's official router, maintained by the same team. It integrates with reactivity and components, and it solves everything that a hand-made router would have to reinvent:

Problem How Vue Router solves it Lesson
Which component to render for each URL A table of routes (path → component) and the <RouterView> component 04-02
Internal links that do not reload <RouterLink>, which intercepts the click and marks the active link 04-02
History and the Back/Forward buttons It manages pushState/popstate (or the hash) for you This lesson
Variable parts of the URL (/rooms/nectar) Route params, accessible reactively 04-03
Screens within screens Nested routes with nested <RouterView>s 04-04
Navigating from code and reading ?filter=... router.push, router.replace and the query 04-05
Blocking or redirecting a navigation (session, unsaved changes) Navigation guards 04-06
Scroll position when changing screen scrollBehavior 04-02
Loading each screen only when it is visited Routes with lazy-loaded components (() => import()) 04-02

In addition, the current route is reactive: if a component displays a piece of data from the URL, it updates on its own when the URL changes, just as with any ref. And Vue DevTools includes a routes panel for inspecting them.

  1. The history modes

When you create the router, you choose how the route is reflected in the URL. Vue Router offers three functions, one per mode:

Function What the URL looks like Mechanism Server configuration When to use it
createWebHistory() colmena.example/rooms/nectar History API (pushState/popstate) Yes: it must return index.html for any route in the application The recommended option for almost every web application
createWebHashHistory() colmena.example/#/rooms/nectar Fragment (#) No Hosting where you cannot configure the server; pages opened from disk (file://)
createMemoryHistory() The browser's URL does not change History kept in memory Not applicable Server-side rendering (SSR), automated tests, applications embedded in another page

4.1 What HTML5 mode requires from the server

With createWebHistory the URLs are clean, but a problem appears as soon as the user reloads or directly opens a link such as colmena.example/rooms/nectar: the browser asks the server for that document, /rooms/nectar, which does not exist as a file. If the server is not prepared, it will respond with a 404 error before Vue Router even gets to run.

flowchart LR
    P["GET /rooms/nectar request"] --> Q{"Is there a file<br/>at that path?"}
    Q -- "Yes (e.g. /assets/app.js)" --> F["Return the file"]
    Q -- "No" --> I["Return index.html<br/>(SPA fallback)"]
    I --> R["Vue Router reads the URL<br/>and renders the room screen"]

The solution is a rewrite rule (a fallback): if the request does not correspond to a real file, the server returns index.html and lets the router decide. Vite's development server already does this for you, so you will not notice anything while you work with npm run dev. You will see how to configure it in Nginx, Apache, Netlify and other hosting services in Deploying Vue.js Applications.

An important consequence: since the server returns index.html for any unknown route, 404 error pages become the application's responsibility. Vue Router has a way of catching any URL that does not match any route; we will use it in the next lesson.

  1. The fundamental pieces

An application with Vue Router relies on four pieces:

Piece What it is Where it appears
routes An array of route records: objects that associate a path with the component to render (and, optionally, a name, params, children, metadata...) In the router configuration
createRouter({ history, routes }) Creates the router instance from the history mode and the routes. It is installed in the application with app.use(router) In the configuration, and in main.js
<RouterView> The slot where the current route's component is rendered. When the URL changes, its content changes In the template of the component that acts as the frame (App.vue)
<RouterLink to="..."> An internal link: it generates a correct <a href>, but intercepts the click to navigate without reloading In any template
flowchart TD
    URL["Browser URL<br/>/rooms"] --> RT["Router instance<br/>(createRouter)"]
    RS["routes<br/>'/' → Home<br/>'/rooms' → Rooms"] --> RT
    RT -->|"current route (reactive)"| RV["RouterView in App.vue"]
    RV --> C["Renders the Rooms component"]
    RL["RouterLink to / "] -->|"click: navigates"| RT
    RT -->|"pushState"| URL

Several things happen when you install the router with app.use(router): RouterView and RouterLink are registered as global components (you can use them in any template without importing them), the router becomes available to the useRouter() and useRoute() composables, and the initial navigation is triggered, which reads the URL the page was opened with and resolves its route.

  1. Installing it in Colmena Bookings

When we created the project in Setting Up the Development Environment, we left the scaffolding tool's Router option unticked so that we could install it by hand and understand each step. The time has come. From the colmena-bookings folder:

npm install vue-router@4
  • vue-router@4 is the branch of Vue Router that is compatible with Vue 3. Branch 3 was the Vue 2 one: if you come across examples with new VueRouter({ mode: 'history' }), they are from that era.
  • It is installed as a production dependency (it goes in dependencies, not in devDependencies), because its code is part of the application that runs in the browser.

Check that it appears in package.json:

{
  "dependencies": {
    "vue": "^3.5.0",
    "vue-router": "^4.5.0"
  }
}

The exact numbers will depend on when you install it; what matters is that vue-router starts with 4. We will not configure it yet: in the next lesson we will create src/router/index.js and reorganise Colmena into views. Before that, it is worth seeing all the pieces in a small, isolated example.

If you are starting a new project, you can tick Router in npm create vue@latest. The scaffolding tool installs Vue Router and creates src/router/index.js and a src/views/ folder with two example views: exactly the structure we will set up by hand.

  1. A minimal example, line by line

To see Vue Router without the noise of a real project, we will use the same approach as in What Is Vue.js?: a single HTML file that loads Vue and Vue Router from a CDN. In any folder (outside colmena-bookings), create a file called routes.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>First steps with Vue Router</title>
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
  <script src="https://unpkg.com/vue-router@4/dist/vue-router.global.js"></script>
  <style>
    nav a { margin-right: 1rem; }
    .router-link-exact-active { font-weight: bold; }
  </style>
</head>
<body>
  <div id="app">
    <h1>Coworking Colmena</h1>
    <nav>
      <router-link to="/">Home</router-link>
      <router-link to="/rooms">Rooms</router-link>
    </nav>
    <router-view></router-view>
  </div>

  <script>
    const { createApp, ref } = Vue
    const { createRouter, createWebHashHistory } = VueRouter

    // 1. The component for each screen
    const Home = {
      template: '<p>Welcome to Colmena. Choose "Rooms" to see the catalogue.</p>'
    }

    const Rooms = {
      setup() {
        const rooms = ref(['Panal Room', 'Polen Room', 'Néctar Room'])
        return { rooms }
      },
      template: '<ul><li v-for="room in rooms" :key="room">{{ room }}</li></ul>'
    }

    // 2. The route table: which component corresponds to each address
    const routes = [
      { path: '/', component: Home },
      { path: '/rooms', component: Rooms }
    ]

    // 3. The router instance
    const router = createRouter({
      history: createWebHashHistory(),
      routes
    })

    // 4. The application, with the router installed
    createApp({}).use(router).mount('#app')
  </script>
</body>
</html>

Open it by double-clicking it in the browser and click the links. Let's analyse it piece by piece.

The two <script src> tags:

  • The first loads the global build of Vue (it creates the Vue variable), the same one as in lesson 01-01.
  • The second loads the global build of Vue Router, which creates the VueRouter variable. It must come after Vue, because it uses it.

The application's frame, inside <div id="app">:

  • <h1> and <nav> are the fixed part: they are visible on every screen.
  • <router-link to="/"> generates an <a href="#/">. When it is clicked, instead of letting the browser follow the link, Vue Router navigates to /. We use the lower-case, hyphenated form (router-link, router-view) because this template is written directly in the HTML and the browser converts tags to lower case; in a .vue file we will write <RouterLink> and <RouterView>.
  • <router-view> is the variable slot: Home or Rooms will appear here depending on the URL.

The script:

  • const { createApp, ref } = Vue and const { createRouter, createWebHashHistory } = VueRouter extract the functions from the global variables. In a Vite project we will import them (import { createRouter } from 'vue-router').
  • Home and Rooms are components written as objects with a template option (Vue compiles those templates in the browser, something the global build allows). Rooms also has a setup() with a ref, like any other component.
  • routes is the array of records. Each one associates a path (the path part of the URL, starting with /) with a component. Notice that we pass the component, not a tag: the router will instantiate it when the time comes.
  • createRouter({ history, routes }) creates the router. We use createWebHashHistory() because we are opening the file from disk: there is no server that can return index.html for /rooms, so we need the mode that does not require one.
  • createApp({}) creates an application with an empty root component: its template is the content of #app. .use(router) installs the router (it registers router-link and router-view and triggers the initial navigation) and .mount('#app') mounts it.

Now carry out these checks:

  1. The URL changes without reloading. Click "Rooms": the address bar ends in #/rooms, and no document request appears in the Network tab of the browser's developer tools.
  2. The history works. Click "Home", then "Rooms" and then the browser's Back button: you return to Home. Forward takes you back to Rooms.
  3. The URLs work on their own. Copy the address with #/rooms, close it and open it again: the list appears straight away.
  4. The active link. The link for the current screen is shown in bold thanks to the router-link-exact-active class, which RouterLink adds on its own. Inspect it: it also carries the aria-current="page" attribute, which tells screen readers which page is the current one.
  5. A route that does not exist. Type #/bookings into the URL by hand: <router-view> is left empty and the console shows a warning (No match found for location with path "/bookings"). No route matches; in the next lesson we will add a 404 page.

  1. Colmena's map of screens

With these pieces, let's plan which screens Colmena Bookings will have by the end of the module. Each screen will be a view, a component in the src/views/ folder, associated with a route. We will give each route a name (name), which lets you link to it without writing its address, as we will see in the next lesson.

Route (path) Name (name) View What it shows Lesson
/ home HomeView A welcome, a summary of free rooms and shortcuts 04-02
/rooms rooms RoomsView The catalogue with filters and its three views (grid, table, map) 04-02; filters in the URL in 04-05
/rooms/:id room-detail RoomDetailView A room's full spec sheet 04-03
/book/:roomId book BookingView The booking form with the room already chosen 04-02 and 04-03
/dashboard dashboard DashboardView The member's personal area, with a fixed side menu; on its own, it leads to the profile 04-04
/dashboard/profile dashboard-profile DashboardProfileView The session details 04-04
/dashboard/bookings dashboard-bookings DashboardBookingsView The bookings created in the session 04-04
/dashboard/invoices dashboard-invoices DashboardInvoicesView Invoicing (managers only) 04-04 and 04-06
/login login LoginView Signing in 04-06
Anything else not-found NotFoundView 404 page 04-02

A few observations about this map:

  • :id and :roomId are dynamic segments: /rooms/nectar and /rooms/polen use the same route and the same view with a different param.
  • /dashboard has child routes: DashboardView renders the side menu and, inside it, the profile, bookings or invoices sub-screen.
  • /dashboard and /book/:roomId will only be accessible when signed in, and /dashboard/invoices only to managers. Navigation guards will make sure of that.
flowchart TD
    App["App.vue<br/>AppHeader + RouterView"]
    App --> I["/ · HomeView"]
    App --> S["/rooms · RoomsView"]
    App --> D["/rooms/:id · RoomDetailView"]
    App --> R["/book/:roomId · BookingView<br/>(requires session)"]
    App --> P["/dashboard · DashboardView (requires session)<br/>side menu + RouterView"]
    App --> L["/login · LoginView"]
    App --> N["/:pathMatch(.*)* · NotFoundView"]
    P --> P1["profile · DashboardProfileView"]
    P --> P2["bookings · DashboardBookingsView"]
    P --> P3["invoices · DashboardInvoicesView<br/>(managers only)"]
    S -. "view spec sheet" .-> D
    D -. "book" .-> R
    R -. "after creating the booking" .-> P2

The dotted arrows are the user's main journeys: from the catalogue to a room's spec sheet, from the spec sheet to the form and, after booking, to the list of their bookings. Today, in the single-page version, that journey happens by scrolling down a long screen; by the end of the module, each step will have its own URL.

Common Mistakes and Tips

  • Installing vue-router without a version in an old project, or following Vue Router 3 tutorials (new VueRouter, mode: 'history', this.$router everywhere). Vue 3 uses branch 4, with createRouter and createWebHistory.
  • Using <a href="/rooms"> for internal links. It works, but it causes a full reload: the in-memory state is lost and the application is downloaded again. To navigate within the SPA, use <RouterLink>. External links (another domain, a PDF) are indeed ordinary <a> elements.
  • Publishing with createWebHistory without configuring the server. Locally everything works (Vite provides the fallback), but in production any reload on an internal route gives a 404. Configure the server or, if you cannot, use createWebHashHistory.
  • Double-clicking to open a project that uses createWebHistory. From file:// there is no server to rewrite routes; in stand-alone examples, use hash mode.
  • Expecting pushState to render something. It only changes the URL; if you build something by hand with the History API, it is up to you to update the screen.
  • Tip: before writing a single route, draw the map of screens, as in section 8. Deciding early on what is a route, what is a child and which parts are fixed avoids painful reorganisations.

Exercises

Exercise 1. Extend routes.html with a third route, /rules, that shows a Rules component with a list of three coworking rules ("Leave the room as you found it", etc.), and with its link in the menu. Then change the styles so that the active link, as well as being bold, is underlined in the colour #e0a100.

Exercise 2. State which history mode you would use in each case and why: (a) Colmena's public booking application, hosted on its own server with Nginx; (b) a small internal dashboard that is delivered as a compressed folder and that employees open by double-clicking; (c) the automated tests of a component that uses <RouterLink>; (d) a static file hosting service that does not allow any rewrite rules.

Exercise 3. Without using Vue Router, write a minimal router with the History API for a page with two screens, / and /rooms, which are rendered in a <main id="screen">. It must: intercept clicks on links with the data-internal attribute, change the URL with pushState, render the screen and react to the Back button. Serve the page with npx vite (or any local server) to try it out. What happens if you reload while on /rooms?

Solutions

Solution 1.

const Rules = {
  template: `
    <ol>
      <li>Leave the room as you found it.</li>
      <li>Keep to the times of your booking.</li>
      <li>Take calls in the Celda Booth.</li>
    </ol>`
}

const routes = [
  { path: '/', component: Home },
  { path: '/rooms', component: Rooms },
  { path: '/rules', component: Rules }
]
<nav>
  <router-link to="/">Home</router-link>
  <router-link to="/rooms">Rooms</router-link>
  <router-link to="/rules">Rules</router-link>
</nav>
.router-link-exact-active {
  font-weight: bold;
  text-decoration: underline;
  text-decoration-color: #e0a100;
}

You only need to touch three places: the component, the route table and the menu. <router-view> does not change: it renders whatever the route says, whatever that is.

Solution 2.

  • (a) createWebHistory: clean, shareable URLs; since we control Nginx, we can add the fallback rule (10-02).
  • (b) createWebHashHistory: it is opened from file://, where there is no server to rewrite routes.
  • (c) createMemoryHistory: tests do not need a real address bar, and each test can start with a clean history (module 8).
  • (d) createWebHashHistory: without rewriting, any reload on an internal route would give a 404 in HTML5 mode.

Solution 3.

<nav>
  <a href="/" data-internal>Home</a>
  <a href="/rooms" data-internal>Rooms</a>
</nav>
<main id="screen"></main>

<script type="module">
  const screens = {
    '/': '<p>Welcome to Colmena.</p>',
    '/rooms': '<p>Catalogue: Panal, Polen, Néctar, Enjambre and Celda.</p>'
  }

  function render(path) {
    document.querySelector('#screen').innerHTML =
      screens[path] ?? '<p>Page not found</p>'
  }

  // Internal links: navigate without reloading
  document.addEventListener('click', (event) => {
    const link = event.target.closest('a[data-internal]')
    if (!link) return
    event.preventDefault()
    const path = link.getAttribute('href')
    history.pushState({}, '', path)
    render(path) // pushState does not render: we do it ourselves
  })

  // Back / Forward
  window.addEventListener('popstate', () => render(location.pathname))

  // Initial navigation
  render(location.pathname)
</script>

With npx vite, reloading on /rooms works because the development server returns index.html for any unknown route (the fallback from section 4.1) and the initial navigation renders the right screen. With a file server without that rule, you would get a 404. Notice everything this router is missing: params, nested routes, guards, scrolling, active links, integration with reactivity... That is what Vue Router brings.

Conclusion

On a multi-page website, the server delivers one document per URL and the history works on its own; in an SPA, the server delivers a single index.html and it is the JavaScript that decides what to render, relying on the History API (pushState, replaceState, popstate) or on the fragment (#) to change the URL without reloading. Vue Router turns that mechanism into a declarative tool: a table of routes that associates addresses with components, a router created with createRouter and one of the three history modes (createWebHistory, the recommended one, with a fallback on the server; createWebHashHistory, with no server requirements; createMemoryHistory, for SSR and tests), the <RouterView> slot and <RouterLink> links, plus the params, nested routes, navigation from code and guards that we will cover over the course of the module. You now have vue-router installed in Colmena and a map of the screens we will build.

The next step is to apply all this to the real project: create src/router/index.js with the first routes, separate the views from the components in the src/views/ folder, share out what App.vue does today between HomeView, RoomsView and BookingView, and leave App.vue as a frame with the header and a <RouterView>. We will do that in Setting Up Vue Router.

New edition · October 2026

Vue.js Course

Module 1: Introduction to Vue.js

Module 2: Vue.js Basics

Module 3: Vue.js Components

Module 4: Vue Router

Module 5: State Management with Vuex and Pinia

Module 6: Vue.js Directives

Module 7: Vue.js Plugins

Module 8: Testing in Vue.js

Module 9: Advanced Vue.js Concepts

Module 10: Building and Deploying Vue.js Applications

Module 11: Real-World Vue.js Projects

© Copyright 2026. All rights reserved