The Official Router for Vue.js

After this lesson you will be able to build the navigation layer of a single-page application with Vue Router 4. You will define static, dynamic and nested routes, protect pages with navigation guards, split your bundle with lazy-loaded routes, and read parameters and query strings the right way - so that a user can share a link to exactly the screen they are looking at.

What the router solves

A single-page application renders one HTML document and swaps the visible component as the user moves around. The browser’s own history still has to follow along, otherwise the back button leaves the site and the address bar never changes.

Vue Router takes care of four things:

  1. Matching the current URL against a table of route definitions.
  2. Rendering the matched component into a RouterView outlet.
  3. Keeping the URL and the history in sync, including the back and forward buttons.
  4. Interrupting navigation when a guard says no.

Installing and creating the router

npm install vue-router@4

A router is created from a history implementation and a list of routes, then installed on the application.

// src/router.js
import { createRouter, createWebHistory } from 'vue-router';

import HomeView from './views/HomeView.vue';

export const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
  ],
});

Install it on the application with app.use(router) before app.mount('#app').

createWebHistory produces clean URLs such as /users/42. It requires the web server to fall back to index.html for unknown paths; if you cannot configure the server, use createWebHashHistory instead, which puts the route after a hash sign in the address bar.

Defining routes

export const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', name: 'home', component: HomeView },
    { path: '/users', name: 'users', component: UserListView },
    { path: '/users/:id', name: 'user-detail', component: UserDetailView },
    { path: '/:pathMatch(.*)*', name: 'not-found', component: NotFoundView },
  ],
});

The last entry is a catch-all: it matches anything that no earlier route claimed, which is how you build a not-found page. It has to stay last, or it swallows every path that follows it.

Linking and rendering

RouterLink renders an anchor tag and intercepts the click so navigation happens without a full page load.

<template>
  <nav>
    <RouterLink to="/">Home</RouterLink>
    <RouterLink :to="{ name: 'user-detail', params: { id: 42 } }">User 42</RouterLink>
  </nav>

  <main>
    <RouterView />
  </main>
</template>

RouterLink adds the router-link-active class to the link whose target matches, and router-link-exact-active when the path matches exactly. Both are useful hooks for styling.

RouterView is the outlet. Whatever route matched is rendered inside it, and it can take a name when several outlets exist on one page.

<RouterView name="sidebar" />

Dynamic routes

A path segment beginning with a colon is a parameter. It matches any value and is available on the route object.

{ path: '/users/:id', name: 'user-detail', component: UserDetailView }
<script setup>
import { useRoute } from 'vue-router';

const route = useRoute();
</script>

<template>
  <h1>User {{ route.params.id }}</h1>
</template>

Parameters can be optional, and several can live in one path: { path: '/users/:id?' } and { path: '/files/:folder/:fileName' }.

Because a parameter is part of the path, it identifies a resource. The rule of thumb: a parameter is part of what the page is, a query string is part of how it is being viewed.

Nested routes

A route can declare children. The child paths are relative, and the resulting full path is the parent path joined with the child path.

{
  path: '/users/:id',
  component: UserLayoutView,
  children: [
    { path: '', name: 'user-profile', component: UserProfileView },
    { path: 'posts', name: 'user-posts', component: UserPostsView },
  ],
}

The parent renders its own RouterView so that the child has somewhere to go.

<!-- UserLayoutView.vue -->
<template>
  <section>
    <h1>User {{ $route.params.id }}</h1>
    <RouterView />
  </section>
</template>

A child route with an empty path is the default view of its parent.

A guard is a function that runs before a navigation is confirmed. It can allow the navigation, block it, or redirect it elsewhere.

router.beforeEach((to, from) => {
  const isLoggedIn = Boolean(localStorage.getItem('token'));

  if (to.meta.requiresAuth && !isLoggedIn) {
    return { name: 'login', query: { redirect: to.fullPath } };
  }

  return true;
});

Three return values matter:

  • true or undefined - continue.
  • false - abort the navigation. The URL stays where it was.
  • a route location object or a string - redirect somewhere else instead.

Per-route guards

Some routes need a check that others do not. beforeEnter on a route definition runs only when that route is the target.

{
  path: '/settings',
  name: 'settings',
  component: SettingsView,
  meta: { requiresAuth: true },
  beforeEnter: (to) => {
    if (!localStorage.getItem('token')) return { name: 'login' };
  },
}

The meta field is a good place to attach data to a route - a required permission, a page title, a breadcrumb label - that guards and layout components can then read.

In-component guards

Some questions can only be answered by the component that is leaving. “The form has unsaved changes” is the classic case.

<script setup>
import { onBeforeRouteLeave } from 'vue-router';

onBeforeRouteLeave(() => {
  return window.confirm('You have unsaved changes. Leave anyway?');
});
</script>

onBeforeRouteUpdate is the sibling for a route that changes but keeps the same component, for example /users/1 to /users/2. Reusing the component instance means route.params changes without a remount, so anything cached from the old parameter must be refreshed: onBeforeRouteUpdate(async (to) => { await loadUser(to.params.id); }).

Order of execution

The router evaluates guards in a fixed order: global beforeEach, then per-route beforeEnter, then in-component guards, then global beforeResolve, and finally the navigation is confirmed. afterEach runs afterwards and cannot block anything, which makes it the right place for analytics.

Lazy loading routes

Route components can be loaded on demand. The lazy form is a function that returns a promise of a module.

{
  path: '/reports',
  name: 'reports',
  component: () => import('./views/ReportsView.vue'),
}

The component is fetched the first time the route is visited and then cached. For a large application this is the single biggest win in initial load time, because the entry bundle no longer contains every screen.

Params against query parameters

// /search?q=vue&page=2
const { q, page } = route.query;

// /users/42
const { id } = route.params;

params are declared in the route path and are matched positionally. query is whatever comes after the question mark and is always a string.

Query values are strings, so convert them explicitly when you need a number.

const page = Number(route.query.page ?? 1);

Building a URL with a query keeps the path clean and lets the user change the view without changing the page.

router.push({ path: '/search', query: { q: 'vue', page: 2 } }) builds the same URL from code.

Programmatic navigation

Inside a component, useRouter gives you the router instance.

<script setup>
import { useRouter } from 'vue-router';

const router = useRouter();

function save() {
  router.push({ name: 'user-detail', params: { id: 42 } });
}
</script>

push adds an entry to the history stack, so the back button returns to the previous screen. replace swaps the current entry instead, which is right for redirects where going back should not return to the intermediate screen. router.back() and router.go(-1) move through the history.

Scroll behaviour and navigation failures

By default the router restores the previous scroll position on back navigation and scrolls to the top on new navigations. You can take over completely with scrollBehavior.

scrollBehavior(to, from, savedPosition) {
  if (savedPosition) return savedPosition;
  if (to.hash) return { el: to.hash, behavior: 'smooth' };
  return { top: 0 };
}

Navigation can also fail, for example when the user clicks the current route again. Vue Router rejects the returned promise with a navigation failure rather than throwing an error, so put await router.push(...) inside a try block and inspect the failure with isNavigationFailure(failure, NavigationFailureType.duplicated) before rethrowing it.

Pitfalls to remember

  • A catch-all route must be last, or it swallows every path that follows it.
  • params are always strings, and so are query values. Convert them.
  • An in-component guard must return false to block; returning nothing allows the navigation.
  • A guard that redirects must not redirect to a route that redirects back, or the router throws a redirect loop.
  • Lazy routes pay their cost on first visit, so a route that is visited immediately after load is often better kept eager.
  • router.push returns a promise that rejects on a blocked or duplicated navigation, so an unhandled rejection can appear in the console.

Practice

Build the router for a small document application with three requirements: a list of documents at /documents, a single document at /documents/:id with a tab for its revisions, a settings page that requires a signed-in user, and a 404 page for anything else.

Write the route table, the guard that protects the settings page, and the way the document page reads its identifier.

Vue RouterNavigation GuardsDynamic RoutesLazy Loading

Approach:

The three requirements map onto three router features: a dynamic segment for the document identifier, meta plus a global guard for the protected page, and a catch-all route placed last for the 404. The revision tab is a nested route, because it shares the document’s layout and its parameter.

Steps:

  1. Static list route. /documents renders the list view.
  2. Dynamic detail route. /documents/:id captures the identifier. The list links to it with a named route and a params object, so a rename of the path never breaks the link.
  3. Nested revision route. A child route with the path revisions under /documents/:id renders inside the document layout’s own RouterView.
  4. Protected route. The settings route carries meta: { requiresAuth: true }, and a global beforeEach checks that flag. Redirects to the login route and carries the original destination in a query so the app can send the user back after signing in.
  5. Catch-all. /:pathMatch(.*)* goes last and renders the not-found view.
  6. Reading the identifier. The document view uses useRoute and reads route.params.id. Because the revision route is nested, the parent layout and the child both see the same parameter.

Answer:

// src/router.js
import { createRouter, createWebHistory } from 'vue-router';
import { isAuthenticated } from './auth';

const view = (name) => () => import(`./views/${name}.vue`);

export const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', name: 'home', component: view('HomeView') },
    { path: '/documents', name: 'documents', component: view('DocumentListView') },
    {
      path: '/documents/:id',
      component: view('DocumentLayoutView'),
      children: [
        { path: '', name: 'document-detail', component: view('DocumentDetailView') },
        { path: 'revisions', name: 'document-revisions', component: view('DocumentRevisionsView') },
      ],
    },
    {
      path: '/settings',
      name: 'settings',
      component: view('SettingsView'),
      meta: { requiresAuth: true },
    },
    { path: '/login', name: 'login', component: view('LoginView') },
    { path: '/:pathMatch(.*)*', name: 'not-found', component: view('NotFoundView') },
  ],

  beforeEach((to) => {
    if (to.meta.requiresAuth && !isAuthenticated()) {
      return { name: 'login', query: { redirect: to.fullPath } };
    }
    return true;
  },
});

The list view links to the detail route with a named route and a params object, so renaming the path never breaks the link:

<RouterLink :to="{ name: 'document-detail', params: { id: doc.id } }">
  {{ doc.title }}
</RouterLink>

The document layout reads the identifier with useRoute() and renders {{ route.params.id }}, plus a RouterLink to the revisions route with the same params and its own RouterView for the nested view.

The identifier is route.params.id in both the layout and the nested views, and the guard keeps the settings page unreachable for anonymous visitors without blocking the rest of the application.

Found an issue with this content?

Tell us what could be improved.