Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Vue Router: setup and routes

Vue Router is the official routing library for Vue. It links the browser address to a page component: / shows the list of posts, /about the "About" page. The page does not reload: the router changes the address and swaps the component.

Installing

In the blog project run:

npm install vue-router

If you tick Router in the feature list when creating a project, create-vue installs the library and creates the files from this lesson itself.

Pages

Page components are usually kept in the src/views/ folder and named with the View suffix. Create src/views/HomeView.vue:

<!-- src/views/HomeView.vue -->
<script setup>
import PostList from '../components/PostList.vue'
</script>
 
<template>
  <h1>Blog</h1>
  <PostList />
</template>

And src/views/AboutView.vue:

<!-- src/views/AboutView.vue -->
<template>
  <h1>About the blog</h1>
  <p>A learning blog built with Vue.</p>
</template>

Describing routes

Create src/router/index.js:

// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import AboutView from '../views/AboutView.vue'
 
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', name: 'home', component: HomeView },
    { path: '/about', name: 'about', component: AboutView },
  ],
})
 
export default router

Each route is an object with an address path, a name name and a component component. createWebHistory enables ordinary addresses like /about, without a hash.

Connecting to the app

In src/main.js add the router with app.use:

// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
 
createApp(App).use(router).mount('#app')

Replace src/App.vue:

<!-- src/App.vue -->
<template>
  <nav>
    <RouterLink to="/">Home</RouterLink> |
    <RouterLink to="/about">About</RouterLink>
  </nav>
  <RouterView />
</template>

RouterView is the place where the current route's component appears. RouterLink renders a link that changes the page without a reload when clicked. Open http://localhost:5173 — you see the menu and the list of posts, and the "About" link changes the address to /about and shows the text about the blog.

The router adds the router-link-active class to the active link — handy for highlighting the current menu item.

Linking by name

Instead of the address you can give the route name:

<RouterLink :to="{ name: 'about' }">About</RouterLink>

If the address later changes to /info, links by name keep working.

Common mistake

Building the menu with plain a tags and href="/about". The link works, but the browser reloads the whole app: state is reset and the page flickers. Use RouterLink for navigation inside the app, and keep a for external sites.

Thanks for reading!

Donate to the site — we work hard for you.