Vue Router Basics

Vue Router matches the page address (the URL) with the component that should show. Make the router with createRouter({ history: createWebHistory(), routes })…

Click "Menu" in the app for Mrs. Sri's stall. The address in the browser changes to /menu, and the page content changes. But the screen doesn't flash white, and the cart still holds 2 items. The browser didn't ask the server for a new page.

Vue Router does this. Vue Router matches the page address (the URL) with the component that should show. So one app can have many "pages" without asking the server for a new page. An app like this is called an SPA (single-page application): there is only one HTML file, and JavaScript swaps its contents. Picture the big menu board at Mrs. Sri's stall, with panels that flip over. A customer says "menu number 2", and Mrs. Sri just flips the panel to Chicken Noodles. The stall isn't rebuilt, and the customer doesn't have to walk out and come back in. In Vue, the number the customer says is the URL, and each panel is a component. Mrs. Sri, who matches the number to a panel, is the router. The frame the panel sits in is <RouterView />: the place where the matching component shows.

Routes: a path to a component

A router is made from a list of routes. Each route pairs a path (the part of the address after the site name, such as /menu) with a component:

// src/router/index.js
import { createRouter, createWebHistory } from "vue-router"
import Home from "../views/Home.vue"
import MenuList from "../views/MenuList.vue"

const routes = [
  { path: "/", component: Home },
  { path: "/menu", component: MenuList },
  { path: "/menu/:id", component: () => import("../views/MenuDetail.vue") },
  { path: "/:pathMatch(.*)*", component: () => import("../views/NotFound.vue") },
]

export const router = createRouter({
  history: createWebHistory(),
  routes,
})

RouterLink and RouterView

This is App.vue with two links and one place for the matching page:

<!-- App.vue -->
<template>
  <nav>
    <RouterLink to="/">Home</RouterLink>
    <RouterLink to="/menu">Menu</RouterLink>
  </nav>
  <RouterView />
</template>

On /menu, the Menu link renders as <a href="/menu" class="router-link-active router-link-exact-active" aria-current="page">Menu</a>.

Click URL <RouterView /> shows Reloaded from the server?
open the app / Home yes, once
RouterLink Menu /menu MenuList no
RouterLink Chicken Noodles /menu/2 MenuDetail no

Route parameters: /menu/:id

The route /menu/:id uses one component, MenuDetail, for every menu item. This is its script:

<!-- MenuDetail.vue -->
<script setup>
import { useRoute, useRouter } from "vue-router"

const route = useRoute()
const router = useRouter()

console.log(route.params.id)   // on /menu/2: "2", text

function goBack() {
  router.push("/menu")
}
</script>

Other options. There are three more things you will often see. The first, name, is on every route in the src/router/index.js file from create-vue (the tool behind the command npm create vue@latest):

{ path: "/menu/:id", name: "menu-detail", component: MenuDetail, props: true }
<RouterLink :to="{ name: 'menu-detail', params: { id: 2 } }">Chicken Noodles</RouterLink>

We tried all three on Vue Router 5.5.1.

The same component is reused

Say MenuDetail loads its menu item in onMounted. On /menu/2 (Chicken Noodles) there's a "Next menu" link to /menu/3. When that link is clicked, the matching route is still /menu/:id, so Vue Router reuses the MenuDetail that already exists. The component isn't created again, and onMounted doesn't run again. The URL and route.params.id are already 3, but the title stays Chicken Noodles. So watch the parameter with a watcher:

const menu = ref(null)

watch(() => route.params.id, (id) => {
  menu.value = menuItems.find((m) => m.id === Number(id))
}, { immediate: true })
Event route.params.id Title without watch Title with watch
open /menu/2 "2" Chicken Noodles Chicken Noodles
click Next menu "3" Chicken Noodles Iced Tea

A 404 page

If no route matches the address, for example /drinks, <RouterView /> shows nothing at all. In development mode, the console writes [VUE_ROUTER_R0004] No match found for location with path "/drinks" in Vue Router 5.3 and later. In earlier versions, including version 4, the message is [Vue Router warn]: No match found for location with path "/drinks". The route { path: "/:pathMatch(.*)*", component: NotFound } matches any address that matches no other route. So a wrong address still gets its own 404 page.

In the exercise editor

The exercise editor loads the real Vue Router (version 4.5.1) as soon as your code uses createRouter. There are two differences from a Vite project (a project made with npm create vue@latest). First, this editor has no main.js, so the router made by createRouter is installed into the app right away, like app.use(router). Second, the preview has no address bar, so createWebHistory() there keeps its address history in memory and always starts at /. New projects from npm create vue@latest get Vue Router 5. The way you use it (its API) is the same as in version 4, so the code in this lesson runs on both. Version 5 also has optional file-based routing (routes made from file names), through the vue-router/vite plugin.

If you click a plain <a href="/about"> in the preview, nothing opens: the editor stops the preview from changing its address, then writes a message to the console. In a real app, a plain <a href> link reloads the whole page, exactly what RouterLink prevents.

📌 Navigation guards

A navigation guard is a function that runs before a move to another page. The function you give to router.beforeEach runs before every move, and to holds the route you are going to. Return false to cancel, another address to redirect, or nothing to continue:

router.beforeEach((to) => {
  if (to.path === "/checkout" && !isLoggedIn.value) return "/login"
})

In this code, a customer who isn't logged in (isLoggedIn.value is false) and is going to /checkout is sent to /login instead.

⚠️ Why did the cart empty, or the title not change?

TL;DR: Vue Router matches the page address (the URL) with the component that should show. Make the router with createRouter({ history: createWebHistory(), routes }). Each route in the routes list is written { path, component }: a part of the address like /menu, and the component that shows there. Then install the router with app.use(router). <RouterLink to="/menu"> moves to another page without reloading, and <RouterView /> shows the matching component. In the route /menu/:id, :id is a parameter (a part of the address that may hold anything). useRoute() gives route.params.id, which is always text, and useRouter() gives the router for router.push() (moving to another page in code). Moving from /menu/2 to /menu/3 reuses the same component, so onMounted doesn't run again: watch the parameter with watch. The route /:pathMatch(.*)* catches unknown addresses, for a 404 page.

⚡ Routes: an address to a component

Write:

const routes = [
  { path: "/", component: Home },
  { path: "/menu", component: MenuList },
  { path: "/menu/:id", component: () => import("../views/MenuDetail.vue") },
]

Meaning: Vue Router matches the page address (the URL) with a component. Every route in the routes list has a path (the part of the address after the site name, such as /menu) and a component (the component that shows at that address). () => import(...) means lazy loading: the component's file is only downloaded when that route is first opened.

⚡ RouterLink and RouterView

Write:

<nav>
  <RouterLink to="/">Home</RouterLink>
  <RouterLink to="/menu">Menu</RouterLink>
</nav>
<RouterView />
Guess first: the cart holds 2 items. If the link is a plain <a href="/menu">, what happens to the cart?

It goes back to 0. The browser asks the server for a new page, and the whole app starts from zero.

Meaning: <RouterLink> still produces an <a href>, but Vue Router catches its click: the URL changes without reloading the page, so the cart still holds 2 items. <RouterView /> is the place where the component that matches the URL shows, and it swaps the component every time the URL changes.

⚡ Parameters and useRoute

Write:

const route = useRoute()
const router = useRouter()

console.log(route.params.id)   // on /menu/2: "2", text

Meaning: In the route /menu/:id, :id is a parameter: a part of the address that may hold anything. useRoute() gives info about the active route: path, params, and query (the part of the address after the ? sign). On /menu/2, route.params.id holds "2". useRouter() gives the router itself, for moving to another page in code: router.push("/menu"). Parameters are always text, so convert with Number(...) before comparing with a number.

What you will learn