Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 87 ยท Routing and Navigation

Build a Tiny Hash Router

Build a working hash-based router with plain Vue reactivity - route table, params, query strings, active links, redirects and a 404 page - in about 60 lines.

You do not need a library to route in Vue. A router is a reactive value (the current location), a function that matches it against a route table, and a component that renders the result. Vue's reactivity connects them: when the location changes, everything that depends on it updates by itself. In this lesson you build one, step by step, and finish with a router that has links, parameters, query strings, redirects and a 404 page.

Building it yourself pays off twice. You get a router for demos and sandboxes where no library is available, and you finally understand what Vue Router does under the hood, which makes its documentation and error messages much easier to read. If routing is new to you, read Routing Concepts first.

We use hash routing: the route lives after the # in the URL (#/users/42). It needs no server setup, and it is the one mode that works inside the sandboxed preview frames used by this site's live examples.

Step 1: the location is reactive state

The browser already tracks the location for us: window.location.hash holds the text after #, and the hashchange event fires whenever it changes, whether the user clicked a link, pressed Back or edited the address bar. All we have to do is copy it into a ref:

sequenceDiagram
  participant U as User
  participant B as Browser
  participant R as location ref
  participant V as Vue render
  U->>B: click link with href #/users
  B->>B: URL hash changes
  B->>R: hashchange event updates the ref
  R->>V: computed route recalculates
  V->>V: router-view renders the new page

The router is a chain of ordinary reactive dependencies. No special "router update" call exists.

Here is the smallest version: three pages, a ref and plain anchors.

The location as a ref

Notice what is absent: there are no click handlers on the links. A hash link is a normal anchor. The browser updates the URL and adds a history entry, so middle click, "open in new tab" and the Back button all work with no extra code. We only react to the result.

Also notice readHash returns "/" when the hash is empty, so the first visit shows the home page.

Step 2: match patterns and extract params

A lookup table like pages[location.value] cannot handle /users/42. We need patterns, just like in Routing Concepts. Each route record gets a path pattern and a component. A :id segment becomes a regular expression group, and the first matching record wins:

JavaScript
function compile(record) {
  const keys = [];
  const source = record.path === "*"
    ? ".*"
    : record.path.replace(/:(\w+)/g, (_, key) => { keys.push(key); return "([^/]+)"; });
  return { ...record, keys, regex: new RegExp("^" + source + "$") };
}

function match(url) {
  const [rawPath, rawQuery = ""] = url.split("?");
  const path = rawPath.replace(/\/+$/, "") || "/";
  for (const record of compiled) {
    const found = record.regex.exec(path);
    if (found) {
      const params = {};
      record.keys.forEach((key, i) => { params[key] = decodeURIComponent(found[i + 1]); });
      return { record, path, params, query: Object.fromEntries(new URLSearchParams(rawQuery)) };
    }
  }
}

The result has everything a page needs: the path, the params from the path and the query from after the ?. We turn it into one route object inside a computed, and give pages a small function, useRoute(), to read it. This mirrors the composable of the same name in Vue Router.

The two building blocks you will use in every Vue Router app are <router-link> and <router-view>. Both are tiny:

  • RouterView renders the component of the current route. It is a render function that returns h(route.value.component). Because it reads the reactive route, it re-renders on every navigation.
  • RouterLink renders an <a href="#..."> and adds an active class when its target matches the current location. A link to /users should also count as active on /users/42, so it checks for an exact match or a path prefix followed by a slash.

If h() is new to you, it is Vue's function for creating virtual nodes; see Render Functions and JSX. Here it simply means "render this component or element."

Step 4: the complete router

Now put it all together. This example has a home page, a users list that sorts through the query string (?sort=desc), a user detail page that reads :id, a redirect from an old URL and a 404 page.

A complete hash router in plain Vue

Spend a few minutes with it and watch the <pre> at the bottom, which prints the current route object:

  • Click Users, then Z to A: the query becomes {"sort":"desc"} and the list reverses. The page did not reload, and no page-specific code listens for the hash: Users just reads route.value.query.
  • Click a person: the Users link in the navigation stays highlighted, because RouterLink treats /users as active for any path that starts with /users/.
  • Click Next user repeatedly, then use the browser Back button. Each push added a history entry.
  • Click Back to list (replace) and then press Back: it skips the detail page you just left, because replace overwrote that entry instead of adding one.
  • Click Old link (redirects): you land on /users and Back does not return to /old-users, because the redirect also used replace. Without it, Back would bounce you into the redirect again and again.
  • Click Broken link, or edit the address bar to #/users/99. The first falls to the catch-all 404, and the second matches the user route but finds no person, so the page itself shows "No such user". Both cases are different: the router decides whether a route exists, your page decides whether the data exists.

Push versus replace

push(to) assigns location.hash, which adds a history entry. replace(to) calls location.replace("#" + to), which overwrites the current entry. Use push for normal navigation, and replace for redirects and for steps the user should not be able to Back into, such as a finished checkout. Vue Router uses the same names: router.push() and router.replace().

One subtle point: assigning the same hash again does not fire hashchange, because nothing changed. That is correct behavior, not a bug.

What this router does not do

Our router is honest about its limits, and the list is a good preview of what Vue Router adds in Vue Router Basics and Vue Router Advanced Features:

  • Nested routes for layouts with a shared shell and a changing inner area.
  • Navigation guards to block or redirect navigation, for example for pages that need a login.
  • Lazy-loaded components that download only when a route is visited.
  • History mode with clean URLs through the History API.
  • Scroll restoration and named routes with typed params.
  • Route ranking: Vue Router picks the most specific match, so the order of your records rarely matters. Ours is first-match-wins.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the minimal router need no click handlers on its links?

    Changing the hash does not reload the page. The browser updates the URL and history, then fires hashchange, which the router copies into a ref so Vue re-renders.
  2. 2. What is the main difference between push and replace?

    Use replace for redirects and steps users should not Back into. Otherwise Back returns to a page that immediately redirects forward again.
  3. 3. What does RouterView render?

    RouterView reads the reactive route inside its render function and renders that route's component, so Vue re-runs it on every navigation.
  4. 4. For #/users/99, who decides that user 99 does not exist?

    Route matching only checks the shape of the URL. Whether the id refers to real data is an application concern, so the page shows its own 'not found' state.

Summary

  • A router is a reactive location, a matcher over a route table, and a component that renders the matched route.
  • Hash routing reads location.hash and listens to hashchange; plain <a href="#/path"> links need no JavaScript.
  • Pattern matching extracts params from the path and a query object from the string after ?.
  • RouterView renders h(route.value.component); RouterLink renders an anchor and computes an active state.
  • push adds a history entry and replace overwrites it; redirects should use replace.
  • A catch-all route handles unknown paths, while missing data is the page's job to report.

Next, see how a real library packages the same ideas: Vue Router Basics.