# Vue Router Basics — Vue.js

Source: https://www.skillbyai.com/en/vue/rt-basics

> Routes, RouterLink, RouterView and params.

## Mapping URLs to components

Vue Router (version 4 for Vue 3) is the official router. You create it with `createRouter`, a history mode such as `createWebHistory()` (clean URLs; the server must fall back to `index.html`) or `createWebHashHistory()`, and an array of **routes** pairing a `path` with a `component`. `<RouterView />` renders the matched component and `<RouterLink to="...">` renders a link that navigates without a full page reload. Dynamic segments like `/users/:id` are available as `route.params.id` through `useRoute()`, and `useRouter()` gives programmatic navigation with `router.push()`. When only the params change, the same component instance is reused, so watch the param to reload data.

## Pages in a single-page app

Vue Router maps URLs to components, guards navigation and loads route code on demand.

![Three ideas: routes and params, guards and lazy loading, nested routes and meta.](assets/figures/vue/section-6-map.svg) — Figure 6.1 — Routes, guards and nested layouts.

## Router setup and a user page

router/index.js and UserPage.vue.

```javascript
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomePage from '@/views/HomePage.vue'
import UserPage from '@/views/UserPage.vue'

export const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', name: 'home', component: HomePage },
    { path: '/users/:id', name: 'user', component: UserPage },
  ],
})
// main.js: app.use(router)

// App.vue template:
// <nav><RouterLink to="/">Home</RouterLink>
//      <RouterLink :to="{ name: 'user', params: { id: 42 } }">User 42</RouterLink></nav>
// <RouterView />

// UserPage.vue <script setup>:
// import { watch } from 'vue'
// import { useRoute, useRouter } from 'vue-router'
// const route = useRoute()
// const router = useRouter()
// watch(() => route.params.id, (id) => loadUser(id), { immediate: true })
// function goHome() { router.push({ name: 'home' }) }
```

## Navigate by route name

Linking with `{ name: 'user', params: { id } }` instead of hand-built strings means URLs can change in one place without breaking links.

**Quiz:** Why should a page watch route.params.id?

- [ ] RouterLink does not update the URL
- [ ] Params are only available after a reload
- [x] The same component instance is reused when only the params change
- [ ] route.params is not reactive

*Answer:* The same component instance is reused when only the params change. Lifecycle hooks like onMounted do not run again.
