Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 87 ยท Routing and Navigation

Vue Router Basics

Learn the essentials of Vue Router - createRouter, routes, router-link, router-view, useRoute, useRouter, named routes and params - with a runnable stand-in.

Vue Router is the official routing library for Vue. You have already built the idea by hand in Build a Tiny Hash Router: a route table, a reactive current route, RouterLink and RouterView. The real library does the same job with more polish: clean URLs through the History API, nested routes, navigation guards, lazy loading, scroll handling and typed route names.

The live editor on this site cannot install npm packages, so Vue Router itself is shown here as read-only code. To make the lesson practical, the runnable example uses a small stand-in with the same API shape: createRouter, router-link, router-view, useRoute, useRouter, named routes and props: true. The code you write on top of it is exactly the code you would write with the real library. Only the import changes.

Installing and creating a router

In a project made with npm create vue@latest (see Ways to Use Vue) you can add the router during setup, or later:

Terminal
npm install vue-router

A router lives in its own module. It needs two things: a history strategy and a list of routes.

JavaScript
// src/router/index.js
import { createRouter, createWebHistory } from "vue-router";
import HomeView from "../views/HomeView.vue";
import UserView from "../views/UserView.vue";

export const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: "/", name: "home", component: HomeView },
    { path: "/users/:id", name: "user", component: UserView, props: true },
    { path: "/:pathMatch(.*)*", name: "not-found", component: () => import("../views/NotFoundView.vue") }
  ]
});
JavaScript
// src/main.js
import { createApp } from "vue";
import App from "./App.vue";
import { router } from "./router";

createApp(App).use(router).mount("#app");

The history option decides how the URL is read and written, as described in Routing Concepts. createWebHistory() gives clean URLs (/users/42) and needs a server fallback. createWebHashHistory() uses #/users/42 and needs no server setup.

Each route record needs a path and a component. Giving it a name is optional but strongly recommended, because navigating by name survives path changes. The last record, /:pathMatch(.*)*, is the catch-all 404: the :pathMatch param captures the rest of the path.

app.use(router) does three things, which the next diagram shows: it registers <RouterLink> and <RouterView> globally, makes $router and $route available in templates, and provides the router to useRouter() and useRoute().

flowchart TD
  A["createApp(App).use(router)"] --> B["Registers RouterLink<br/>and RouterView globally"]
  A --> C["Adds $router and $route<br/>to every template"]
  A --> D["Provides router and route<br/>to useRouter() / useRoute()"]
  E["URL changes"] --> F["Router matches a route record"]
  F --> G["RouterView renders<br/>that record's component"]

Installing the router wires three things into the app; after that, every URL change flows to RouterView.

An app shell with navigation and a place for the current page is just two components:

VUE
<!-- App.vue -->
<script setup>
import { RouterLink, RouterView } from "vue-router";
</script>

<template>
  <nav>
    <RouterLink to="/">Home</RouterLink>
    <RouterLink :to="{ name: 'user', params: { id: 42 } }">Ada</RouterLink>
  </nav>
  <RouterView />
</template>
  • <RouterLink> renders a real <a href>, so middle click and "open in new tab" work. It intercepts normal clicks to navigate without reloading. It adds router-link-active when the current route starts with its target, and router-link-exact-active when it matches exactly (with aria-current="page" on the exact one). You can style both.
  • <RouterView> renders the component of the matched route. When you navigate, it swaps the component, and you can wrap it in <Transition> for page animations.
  • The to prop takes a string ("/users/42") or an object. Prefer the object form with name and params: you never glue strings together, and parameters are encoded correctly.

Never use a plain <a href="/users/42"> for in-app links with history mode: it would trigger a full page load and throw away your app state.

Reading the route and navigating from code

Inside <script setup> two composables give you the two sides of the router:

VUE
<!-- UserView.vue -->
<script setup>
import { computed, watch } from "vue";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();   // where am I? (reactive)
const router = useRouter(); // go somewhere else

const tab = computed(() => route.query.tab ?? "profile");

watch(() => route.params.id, (id) => {
  console.log("now showing user", id);
});

function openNext() {
  router.push({ name: "user", params: { id: Number(route.params.id) + 1 }, query: { tab: "posts" } });
}
</script>
  • useRoute() returns a reactive object with path, fullPath, name, params, query, hash and meta. Read it inside computed or watch, as above, to react to changes. Do not destructure it: const { params } = route takes a snapshot and loses reactivity (see Reactivity Pitfalls).
  • useRouter() returns the router instance: push, replace, back, go and so on. push adds a history entry and replace overwrites the current one, exactly as in our hand-made router.
  • In the Options API the same objects are this.$route and this.$router.

Params as props

Reading useRoute().params.id ties a page to the router. With props: true on the record, route params arrive as props instead, which makes the page easier to reuse and test:

VUE
<script setup>
defineProps({ id: String });
</script>

Params are always strings. Convert with Number() when you need a number.

A runnable stand-in

Here is a complete app written against the Vue Router API, running on a small stand-in router (the first block in the code, about 55 lines). Read the stand-in once, then focus on the second half: the pages, the route table, useRoute, useRouter, named links and props: true.

Vue Router-style app on a stand-in router

Try this sequence:

  1. Click Users, then Ada Lovelace. The Users link keeps its bold router-link-active style while the page is a child path, but only exact matches get the underline (router-link-exact-active).
  2. Click Next user twice. The page title changes, the log records id changed from 1 to 2 and so on, but the component instance number stays 1. This is the most important behavior to remember about params, and the next section explains it.
  3. Go back to Users and press the router.push button. The URL gets a query string, and the detail page reads tab = posts from route.query.
  4. Click Old link: the redirect record sends you to /users. Click Broken to see the catch-all route.

Same component, new params

When you move from /users/1 to /users/2, both URLs match the same route record. Vue Router (and our stand-in) reuses the existing component instance instead of destroying and recreating it, because that is more efficient. The consequence: onMounted does not run again, and any code in setup that read the param once is now stale.

flowchart LR
  A["/users/1<br/>instance created, onMounted runs"] -->|"navigate to /users/2"| B["Same record matches<br/>instance is reused"]
  B --> C["route.params.id changes<br/>computed and watch react"]
  B -.->|"does not happen"| D["onMounted runs again"]

Reactive route values update on reuse; one-time setup code does not run again.

So load data with a watch (or a computed) on route.params.id, not just in onMounted. In UserView.vue above that is the watch(() => route.params.id, ...) call. If you ever want a full reset per param, put a :key="route.fullPath" on <RouterView>, at the cost of re-creating the component each time. Data-loading patterns appear in Fetching Data.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is { name: 'user', params: { id: 42 } } usually better than the string '/users/42' in a RouterLink?

    If the path of a route changes later, every name-based link keeps working. Params are also URL-encoded for you.
  2. 2. You navigate from /users/1 to /users/2, both matching one record. What happens to the page component?

    Reuse is an optimization. Code that reads the param once in setup or onMounted goes stale, so watch the reactive route.
  3. 3. What does useRoute() return, and what should you avoid doing with it?

    useRoute() is reactive. Destructuring params or query takes a plain snapshot. Read them through route inside computed or watch.
  4. 4. What is props: true on a route record for?

    The page receives id as a normal prop, so it does not need to import useRoute and is easier to test and reuse.

Summary

  • Vue Router is the official router: createRouter({ history, routes }), installed with app.use(router).
  • createWebHistory() gives clean URLs and needs a server fallback; createWebHashHistory() needs none.
  • <RouterLink> renders a real anchor with active classes; <RouterView> renders the matched component.
  • Prefer named routes with params and query objects over concatenated strings.
  • useRoute() is the reactive current route (do not destructure it); useRouter() gives push, replace and back.
  • props: true passes params as props; params are strings.
  • Navigating between URLs of the same record reuses the component, so react to params with watch or computed.

Next: nested layouts, guards and lazy routes in Vue Router Advanced Features.