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,
})
- Every route has a
pathand acomponent(the component that shows at that address). component: () => import("...")is lazy loading: the component's file is only downloaded when that route is first opened, so the first page is faster.createRouter()makes the router from therouteslist. Thehistoryoption decides what the URLs look like.createWebHistory()makes clean URLs like/menu/2. When you reload/menu/2, the browser asks the server for that address. So the server must sendindex.html, the app's only HTML file, for every address. Otherwise the server answers 404 (page not found).createWebHashHistory()makes URLs like/#/menu/2that need no server setup, because the part after#is not sent to the server.- In
src/main.js,createApp(App).use(router).mount("#app")installs the router in the app. Vue Router is a package separate from Vue. Add it to your project with the commandnpm install vue-routerin the terminal.
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 |
<RouterLink to="...">produces a plain<a href>, but Vue Router catches its click. Vue Router changes the URL through the History API (a browser feature that changes the address without loading a new page), then<RouterView />swaps its component. The page isn't reloaded, so state like the cart stays.- A plain
<a href="/menu">makes the browser ask the server for a new page. The whole app starts from zero, and the cart goes back to 0. - A link that matches the current URL gets the class
router-link-active, so the active menu item is easy to style.
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>
:idin a path is a parameter: a part of the URL that may hold anything./menu/2matches/menu/:id, androute.params.idholds"2".- Parameters are always text. Say
menuItemsis an array of the stall's menu items, and each item'sidis a number. A search withmenuItems.find((m) => m.id === route.params.id)never finds the item, because2 === "2"isfalse. Convert it to a number first:Number(route.params.id). useRoute()gives info about the active route:path,params, andquery(the part of the address after the?sign).useRouter()gives the router itself, for moving to another page in code:router.push("/menu"), orrouter.back()to go back to the previous page.
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>
- Named routes (
name): a link names the route, not its address. The link above still becomes<a href="/menu/2">. If the path changes later, the link doesn't need to change. props: true: the parameter is passed as a prop.MenuDetailonly needsdefineProps({ id: String }), with nouseRoute(). It is still text,"2".- Nested routes (
children, routes inside a route): say the route/menu/:idgetschildren: [{ path: "reviews", component: MenuReviews }]. The address/menu/2/reviewsthen showsMenuReviewsin the<RouterView />inside the template ofMenuDetail.
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.
- In the first exercise, you make a router with two routes,
<RouterLink id="home-link">and<RouterLink id="about-link">, then<RouterView />. The checker clicks the links and reads#page. - In the second exercise, you add the route
/profile/:nameand read its parameter withuseRoute(). Soh2#currentreadsProfile budiafter the Budi link is clicked.
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?
<a href>to move between pages inside the app. The whole app reloads, and state is lost. Use<RouterLink to>.- Expecting the component to be recreated when a parameter changes. Moving from
/menu/2to/menu/3uses the same component. Watch() => route.params.id. - Comparing a parameter with a number.
route.params.idis text. UseNumber(...). - Forgetting the 404 route. An unknown address shows an empty page. Add the route
/:pathMatch(.*)*. - Text and ids different from the brief. The first exercise checks
#home-link,#about-link, and#pageholdingHome Pageand thenAbout Page. The second exercise checks#navwith at least 3 links, andh2#currentreadingHome,Profile budi, orProfile saridepending on the link clicked.
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.