Vue Router fundamentals
Installing Vue Router as a plugin, declaring routes with createRouter, rendering them with RouterView and RouterLink, and changing pages from code.
Vue Router fundamentals
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `createRouter({ history, routes })` builds the router from two decisions: how URLs are stored (`createWebHistory()` for real paths, `createWebHashHistory()` for `#/` URLs) and a `routes` array pairing each `path` with a `component`.
- `app.use(router)` installs it as a plugin: it registers `<RouterLink>` and `<RouterView>` globally, exposes `$route` and `$router` to templates, and starts the first navigation.
- `<RouterView />` is the hole in your layout where the matched route's component renders; `<RouterLink to="...">` renders a real `<a href>` but switches pages without a reload and adds `router-link-active` / `router-link-exact-active` classes.
- Inside `<script setup>`, `useRoute()` gives you the current location (reactive: `path`, `params`, `query`, `name`, `meta`) and `useRouter()` gives you the router instance for `push`, `replace`, and `back`.
- Name your routes and link to them with `{ name: 'job', params: { id } }` instead of hand-built strings, so renaming a URL later is a one-line change in the route table.
- Vue Router 5 (January 2026) kept the version 4 API unchanged and folded in optional file-based routing through `vue-router/vite`; the hand-written `routes` array taught here is still the core model underneath it.
What a router adds on top of the History API
The frontend roadmap’s lesson on client-side routing built the mechanism by hand: intercept link clicks, call history.pushState, listen for popstate, decide what to render from the new URL. Every single-page app needs that loop, and nobody wants to rewrite it per project.
Vue Router is the official package that owns the loop for you. You hand it a table of URL patterns and components. It does the matching, intercepts the clicks, keeps the browser’s back button working, and exposes the current location as reactive state. That last part is the Vue-specific piece. Because the current route is reactive, any template or computed that reads it re-renders when the URL changes. No event listeners to wire up.
Think of it like the departures board at a train station. You don’t ask each platform what is leaving — you read one board that updates itself, and everything downstream (the announcements, the gate signs) follows it.
Declaring the route table
A project made with npm create vue@latest and the router option ticked gets a file like this. If you add the router later, it is npm install vue-router and the same file written by hand:
// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/views/HomeView.vue'
import JobsView from '@/views/JobsView.vue'
import NotFoundView from '@/views/NotFoundView.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{ path: '/', name: 'home', component: HomeView },
{ path: '/jobs', name: 'jobs', component: JobsView },
{
path: '/about',
name: 'about',
// loaded only when someone visits /about
component: () => import('@/views/AboutView.vue'),
},
{ path: '/:pathMatch(.*)*', name: 'not-found', component: NotFoundView },
],
})
export default router
Two decisions live here. history picks how locations are stored. createWebHistory() gives clean paths like /jobs and needs the server to serve index.html for unknown paths. createWebHashHistory() puts the route after a # (/#/jobs), which works on any static host with no server rules. createMemoryHistory() keeps the location in memory only, for server rendering and tests.
routes is the table. Each record pairs a path with a component, and an optional name. The arrow-function component on /about is a lazy route: the bundler splits it into its own chunk and the router fetches it on first visit. That pattern is plain dynamic import() — the router handles the waiting itself, so you don’t wrap it in defineAsyncComponent. The last record is a catch-all that turns every unmatched URL into a 404 page. The next lesson unpacks that odd-looking path.
Installing it as a plugin
The router does nothing until the app uses it:
// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')
This is the plugin pattern you have already met. app.use(router) registers the RouterLink and RouterView components globally, provides the router to every component (which is what useRouter() and useRoute() inject), adds $router and $route to templates, and triggers the initial navigation to whatever URL the page loaded on.
RouterView and RouterLink
The root component decides where routed content goes:
<!-- src/App.vue -->
<script setup>
import { RouterLink, RouterView } from 'vue-router'
</script>
<template>
<nav>
<RouterLink to="/">Home</RouterLink>
<RouterLink :to="{ name: 'jobs' }">Jobs</RouterLink>
</nav>
<main>
<RouterView />
</main>
</template>
<RouterView /> is a placeholder. Whatever component matches the current URL renders in its place, and the <nav> around it stays mounted across navigations. Importing RouterLink and RouterView explicitly is optional, since the plugin registered them globally. It does help editors and type-checking.
<RouterLink> renders a genuine <a href="/jobs">. A plain left click is intercepted and turned into a router navigation. A middle-click or Ctrl-click falls through to the browser and opens a new tab, as a link should. It also tags itself with CSS classes. router-link-active goes on any link whose target is a parent of (or equal to) the current route. router-link-exact-active goes only on an exact match. That gives you nav highlighting for free:
nav a.router-link-exact-active {
font-weight: 600;
border-bottom: 2px solid currentColor;
}
Reading and changing the route from code
Templates can read $route directly. In <script setup> you use two composables instead, and the split between them is worth getting right. useRoute() is the current location: a reactive object with path, fullPath, params, query, hash, name, and meta. useRouter() is the router itself: the object with methods that change the location.
<script setup>
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
const isHome = computed(() => route.name === 'home')
async function save(job) {
await api.saveJob(job)
router.push({ name: 'jobs' }) // add a history entry
}
function cancel() {
router.back() // same as the browser back button
}
</script>
router.push adds a history entry. router.replace swaps the current one, so Back skips it — useful after a login redirect. router.go(n) moves through history like history.go. push returns a Promise that settles once the navigation finishes (or is blocked by a guard, covered in navigation guards), so you can await it when the next line depends on the new page.
Prefer route names over string paths. router.push({ name: 'job', params: { id: 42 } }) keeps working if /jobs/:id later becomes /careers/:id. A hand-built `/jobs/${id}` string scattered across twenty components does not.
If you are coming from React Router, the mapping is direct. <RouterView> plays the role of <Outlet> and <Routes>, useRouter().push is useNavigate(), and useRoute() covers what useLocation() and useParams() split between them.
Version note: Vue Router 5 and file-based routes
The current major is Vue Router 5, released in January 2026. The maintainers describe it as a deliberately boring release. For anyone using the version 4 API it has no breaking changes. What it adds is the file-based routing plugin that used to live in the separate unplugin-vue-router package. With vue-router/vite in your Vite config, files under src/pages become routes (src/pages/users/[id].vue → /users/:id), and route names and params get generated TypeScript types. You import the generated table from vue-router/auto-routes and pass it to the same createRouter call.
That plugin is optional. Most existing codebases, tutorials, and the video for this lesson write the routes array by hand, and the generated version produces the same records. Learn the array first. Nuxt builds its own file-based routing on the same router, which you’ll meet at the end of this roadmap.
What the video covers
Brad Traversy’s crash course reaches routing at 1:32:35, and the embed starts there. Over roughly 24 minutes he installs Vue Router into a create-vue project, builds the route table, swaps the hard-coded home page for a <RouterView>, and replaces anchors with <RouterLink>. He then highlights the active nav item by comparing useRoute().path in the navbar and adds a catch-all Not Found page. Everything is <script setup> and the current version 4 API. Programmatic navigation with useRouter().push shows up later in the same course, when the job form submits. The section above covers it, so you don’t need to keep watching. The route params his job pages use are the subject of the next lesson.
Check yourself
What are the two required options to `createRouter`, and what does each decide?
`history` decides how the current location is stored and read — `createWebHistory()` uses real paths via the History API, `createWebHashHistory()` keeps the route after a `#` so no server configuration is needed. `routes` is the array of route records, each mapping a `path` pattern to the `component` that should render when it matches.
Why does a `<RouterLink>` not trigger a full page reload, while still being safe for middle-click and screen readers?
It renders an ordinary `<a>` element with a real `href`, so the browser and assistive technology treat it as a link and modified clicks open a new tab. On a plain left click it calls `preventDefault()` and asks the router to push the new location instead, so only the `<RouterView>` content changes.
In a `<script setup>` component, which composable do you call to read the current URL's query string, and which to redirect after a form submits?
`useRoute()` returns the reactive current route, so `route.query` holds the query string as an object. `useRouter()` returns the router instance, and `router.push('/somewhere')` or `router.push({ name: 'somewhere' })` performs the redirect.
You set `createWebHistory()` and deploy, and refreshing `/jobs/3` returns a 404 from the server. What is wrong?
With HTML5 history the browser requests `/jobs/3` from the server on a refresh, and the server has no such file. The server needs a fallback rule that serves `index.html` for unknown paths so the Vue app boots and the router resolves `/jobs/3` itself. Hash history avoids this because everything after `#` never reaches the server.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.