Vue Router Basics
Setting up client-side routing with Vue Router, and how it maps URLs to components without full page reloads.
2 min de lecture
Vue itself has no concept of a URL — a Vue app without a router is a single page, and everything you've built so far in this course lives entirely inside App.vue. Vue Router is the official library that maps URL paths to components, giving you a multi-"page" application that's still, technically, a single page that never fully reloads.
Installing and configuring
npm install vue-router// src/router/index.js
import { createRouter, createWebHistory } from "vue-router";
import HomePage from "../views/HomePage.vue";
import AboutPage from "../views/AboutPage.vue";
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: "/", component: HomePage },
{ path: "/about", component: AboutPage },
],
});
export default router;// src/main.js
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
createApp(App).use(router).mount("#app");createWebHistory() uses the browser's real History API, giving you clean URLs (/about, not /#/about) — this requires your production server to be configured to serve index.html for unknown paths, since a hard refresh on /about is still a real HTTP request the server has to answer.
app.use(router) registers the router as a plugin — Vue's mechanism for adding app-wide functionality. It's the same pattern Pinia uses in the next lessons.
Rendering the matched route
<!-- App.vue -->
<script setup>
import { RouterLink, RouterView } from "vue-router";
</script>
<template>
<nav>
<RouterLink to="/">Home</RouterLink>
<RouterLink to="/about">About</RouterLink>
</nav>
<RouterView />
</template><RouterView> is where the component for the currently matched route renders — think of it as a <slot> the router fills in based on the URL. <RouterLink> renders an <a> tag but intercepts the click to update the route via JavaScript instead of triggering a full page navigation, which is what keeps the app from reloading (and losing all its in-memory state) on every link click.
Why not just use <a href="/about">?
A plain anchor tag works, technically — the browser would load /about and, assuming your server serves the same index.html for every path, Vue Router would pick up from there. But that's a full page reload: the whole JavaScript bundle re-downloads and re-executes, every component remounts from scratch, and any in-memory state (a shopping cart the user built up, an open modal) is lost. <RouterLink> avoids all of that — the "navigation" is really just Vue swapping which component <RouterView> renders, with the URL updated to match.
The next lesson covers dynamic route segments (/products/:id) and navigating programmatically from your <script setup> code, not just from template links.