Introduction to Vue Router

May 27, 2019

Vue Router is Vue's official router. The point of a router is to integrate a single page app with browser navigation, like the back button.

Here's how you create a page with 2 links using Vue Router. First, example1.html:

    <script src=""></script>
    <script src=""></script>

    <div id="content"></div>
    <script src="example1.js"></script>

This script loads example1.js. Below is the example1.js file:

const router = new VueRouter({
  routes: [
    // A route maps paths to components - when the portion of the URL after
    // '#' changes, Vue router changes which component is displayed
      path: '/home',
      component: { template: '<h1>Home</h1>' }
      path: '/about',
      component: { template: '<h1>About Us</h1>' }

const app = new Vue({
  // The `router-link` and `router-view` components are from Vue router.
  // `router-link` becomes an <a> that links to the correct path
  // `router-view` is where Vue router renders the component or template
  // that corresponds to the current path.
  template: `
    <div id="rendered-content">
        <router-link to="/home">Home</router-link>
        <router-link to="/about">About Us</router-link>

Here's a live example of this basic Vue router setup. Below is a video of this code in action.


There's numerous ways to test Vue apps. One alternative approach is using Segment's browser automation tool Nightmare. Here's the Mocha test we use to test the example from this article:

  describe('router', function() {
    it('basic example', async function() {
      const nightmare = new Nightmare({ show: false });

      await nightmare.

      let res = await nightmare.evaluate(() => document.querySelector('h1').innerHTML);
      assert.equal(res, 'Home');

      res = await nightmare.evaluate(() => document.querySelector('h1').innerHTML);
      assert.equal(res, 'About Us');

      await nightmare.end();

Vue School has some of our favorite Vue video courses. Their Vue.js Master Class walks you through building a real world application, and does a great job of teaching you how to integrate Vue with Firebase. Check it out!

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Vue Tutorials