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:

<html>
  <head>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
  </head>

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

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({
  router,
  // 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">
      <div>
        <router-link to="/home">Home</router-link>
        <router-link to="/about">About Us</router-link>
      </div>
      <div>
        <router-view></router-view>
      </div>
    </div>
  `
}).$mount('#content');

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

Testing

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.
        goto(`file://${process.cwd()}/tutorials/vue/router/example1.html`).
        wait('#rendered-content');

      await nightmare.click('a[href="#/home"]');
      let res = await nightmare.evaluate(() => document.querySelector('h1').innerHTML);
      assert.equal(res, 'Home');

      await nightmare.click('a[href="#/about"]');
      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