Chapter 5. Client-Side Routing with vue-router

With the core Vue.js library introduced in the previous chapters, we can display and work with data on a page. However, a fully featured website requires more than just that. You may have noticed on some websites that you can navigate around the site without downloading the new page from the server, or if you’ve used another framework before, you’ve probably already met client-side routing.

vue-router is a library for Vue that means we can handle the routing of an app in the browser instead of on the server as in traditional websites. Routing is the act of taking a path (for example, /users/12345/posts) and deciding what should be displayed on the page.

Installation

As with Vue itself, there are multiple ways to install vue-router. You can use a CDN by adding the following:

<script src="https://unpkg.com/vue-router"></script>

Or if you’re using npm, you can install it using npm install --save vue-router. Then, if you’re using a bundler such as webpack, you will need to call Vue.use(VueRouter) to install vue-router:

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

Vue.use(VueRouter);

This step adds components to your app that you will meet in the next few sections.

Basic Usage

To set up the router, you need to give it an array of paths and the corresponding components: when the path is matched, the component will be displayed.

The following creates a simple two-path router:

import PageHome from './components/pages/Home' ...

Get Vue.js: Up and Running now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.