O'Reilly logo

Vue.js: Up and Running by Callum Macrae

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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' ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required