Getting Started with Vue Router

Learn what single-page applications are, how client-side routing works, and how to install, configure, and use Vue Router in a Vue 2.0 project.

🎯 Introduction

By the end of this article, you will understand the basics of single-page applications (SPAs) and the role of client-side routing. You will also learn to install and use Vue Router in a Vue 2.0 project, configure routes, display pages with <router-view>, and navigate with <router-link>. These are your first steps toward building a modern SPA!


🛤️ What Is a Single-Page Application?

SPA stands for Single Page Application. It is an architecture for web applications. On a traditional website, clicking a link reloads the entire page and loads a new HTML file.

In an SPA, content is displayed within a single HTML page, and JavaScript handles page changes dynamically on the client. For example, clicking “About Us” in the navigation displays information about the organization without reloading the entire page.

This approach offers several benefits:

  • A smoother user experience, with fast navigation and no flashes of a blank page;
  • Less work for the server, as data is fetched through APIs while the page structure stays in place;
  • More flexible control over page state and interactions.
Think of an SPA as an e-book: turning a page updates the content in the same reader, rather than requiring you to buy a new book each time.

🌐 What Is Client-Side Routing?

Client-side routing is a core part of an SPA. It tracks changes to the browser URL, such as /home or /about, and displays the corresponding page component without reloading the entire page.

The URL in the address bar identifies a page. The client-side router uses that address to decide which content to display.

Traditionally, a server handles routing: requesting a URL returns the corresponding page. In an SPA, the client handles this process, hence the term “client-side routing.”

  • Track URL changes using hash or history mode
  • Render the matching component based on the route configuration
  • Navigate between pages without reloading
Client-side routing is like an e-book's table of contents: selecting a chapter changes the content without downloading the whole book again.

🧭 Introducing Vue Router

Vue Router is the official routing library for Vue.js. It handles navigation and route management in single-page applications.

Vue Router 3 is designed for Vue 2.x and provides:

  • A straightforward route configuration format
  • Multiple routing modes: hash and history
  • A built-in <router-view> component for rendering the matched component
  • A <router-link> component for creating navigation links
  • Advanced features such as navigation guards and dynamic route matching

Vue Router simplifies navigation management and integrates with Vue's reactivity system.


⚙️ Installing and Injecting Vue Router

Installing Vue Router

In Vue 2.x projects, Vue Router is usually installed separately. You can use npm or yarn; the npm command is:

npm install vue-router@3

Use Vue Router 3 for Vue 2.x. Vue Router 4 is intended for Vue 3.

Importing and Injecting the Router

Create a router.js file to configure the router instance:

router.js
import Vue from 'vue';
import VueRouter from 'vue-router';

// Install the VueRouter plugin
Vue.use(VueRouter);

// Import route components (configured in more detail below)
import Home from './components/Home.vue';
import About from './components/About.vue';

// Define the route configuration
const routes = [
    { path: '/', component: Home },
    { path: '/about', component: About },
];

// Create the router instance
const router = new VueRouter({
    mode: 'hash', // Default hash mode; 'history' is also available
    routes,
});

export default router;

Inject the router in main.js:

main.js
import Vue from 'vue';
import App from './App.vue';
import router from './router.js';

new Vue({
    el: '#app',
    router, // Inject the router
    render: h => h(App),
});

The Vue instance can now respond to URL changes and load the corresponding components automatically.


🗺️ Configuring Routes (the routes Array)

The route configuration is the foundation of routing. It maps URLs to components.

const routes = [
    {
        path: '/',
        component: Home,
    },
    {
        path: '/about',
        component: About,
    },
    {
        path: '/user/:id', // Dynamic route matching paths such as /user/123
        component: UserProfile,
    },
];
  • path specifies the URL path
  • component specifies the corresponding Vue component
  • Dynamic path parameters, such as :id, are supported
  • You can also configure nested routes, redirects, and more

<router-view>

This built-in Vue Router component acts as a placeholder. When the route changes, the matching component is rendered here.

In the root component, App.vue:

App.vue
<template>
    <div id="app">
        <h1>My Vue SPA</h1>
        <nav>
            <router-link to="/">Home</router-link>
            <router-link to="/about">About</router-link>
        </nav>
        <router-view></router-view>
        <!-- Render the matched component -->
    </div>
</template>

<router-view> is the page's content area, displaying a different component for each matching route.

This navigation link component replaces a regular <a> element and creates links that work with the router.

The to prop specifies the destination path:

<router-link to="/about">About Us</router-link>

It renders as:

<a href="#/about">About Us</a>

Clicking the link triggers navigation without reloading the page.

Use <router-link> for smoother navigation without the flicker of a full page reload.

❓ Questions and Answers

Q1: Why use <router-link> instead of a regular <a> element with Vue Router?

Clicking <router-link> calls Vue Router's navigation methods instead of triggering a full page reload. This provides a smoother navigation experience in an SPA.

Q2: How do you define a dynamic route with parameters?

Add a colon-prefixed parameter to the path, such as /user/:id. When you visit /user/123, the id parameter is 123, accessible in the component through $route.params.id.


🧪 Exercises

Exercise 1 - Configure Routes

Add the following routes to an existing Vue 2 project:

  • / displays the Home component
  • /about displays the About component
  • /profile/:username displays the Profile component
import Home from './components/Home.vue';
import About from './components/About.vue';
import Profile from './components/Profile.vue';

const routes = [
    // Write your code here
];

Complete App.vue with a navigation bar and a route view:

<template>
    <div id="app">
        <nav>
            <!-- Add your navigation links here -->
        </nav>
        <!-- Route view placeholder -->
    </div>
</template>

<script>
export default {
    name: 'App',
};
</script>

🎉 You now understand SPA basics, client-side routing, and how to install and use Vue Router! Use these skills to build smoother single-page applications, and keep practicing!