Introduction to Vue Router

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 : [ { path : '/home' , component : { template : '<h1>Home</h1>' } }, { path : '/about' , component : { template : '<h1>About Us</h1>' } } ] }); const app = new Vue({ router, 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(); }); });

More Vue Tutorials