VueJS: Vue Router

in VueJS Router

An important part of a JavaScript website is the ability to show different content depending on the URL you navigate to. In traditional web development this URL will point to a flat HTML file and be displayed by the browser. In JavaScript development the URL will always point to the base file then this URL is parsed and the JavaScript router will display the correct component defined for this route.

With VueJS this is no different, Vue has a library for the VueRouter allowing you to change the component on the page which can be used for single page websites.

Installation

There are a few ways you install the vue-router library you can include the file from a CDN.

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

Or you can install vue-router from using NPM.

npm install vue-router

Then you will need to load this into Vue by using the Vue.use() method.

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

Vue.use(VueRouter)

Getting Started

To get started with Vue Router is very simple, all you have to do is create a new Vue router then inject this into the Vue object to make the app router aware.

var router = new VueRouter({
  routes: []
})

var app = new Vue({
  router
}).$mount('#app')

Defining The Routes

To define the routes inside the VueRouter object you need to pass in an array of objects that define the path and the component to use.

var router = new VueRouter({
  routes: [
     { path: '/', component: require('./components/home.vue') },
     { path: '/about', component: require('./components/about.vue') },
     { path: '/contact', component: require('./components/contact.vue') },
  ]
})

Now when you navigate to / it will display the home component, when navigating to /about the about component is displayed, /contact will in turn display the contact component.

This works by Vue replacing a HTML tag with the HTML of the component.

Linking To A Page

To link to a page defined in the VueRouter you need to use a new HTML tag of passing in a attribute of to which defines where the path navigates to.

<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
<router-link to="/contact">Contact</router-link>

Building A Demo Page

With understanding the basic usage of the VueRouter let's build the page to display the Homepage, About Us page and Contact page.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset='UTF-8'>
        <meta name="robots" content="noindex">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <link href="../assets/css/styles.css" rel="stylesheet">

    </head>
    <body>
    <div id="app">
        <h1>Router Example</h1>
        <p>
            <router-link to="/">Home</router-link>
            <router-link to="/about">About</router-link>
            <router-link to="/contact">Contact</router-link>
        </p>
        <router-view></router-view>
    </div>

<script src='https://unpkg.com/vue@next/dist/vue.js'></script>
<script src='https://unpkg.com/vue-router@next'></script>
<script src="js/app.js"></script>
</body>
</html>

With the example HTML in place we need to include the Javascript used inside the app.js file.

const Home = { template: '<div class="container"><h1>Home</h1></div>' };
const About = { template: '<div class="container"><h1>About</h1></div>' };
const Contact = { template: '<div class="container"><h1>Contact</h1></div>' };

const routes = [
    {
        path: '/',
        component: Home
    },
    {
        path: '/about',
        component: About
    },
    {
        path: '/contact',
        component: Contact
    }
];
const router = new VueRouter({ routes: routes });
const app = new Vue({ router }).$mount('#app');

View the demo to see this page in action.

Demo

Named Routes

It's good practice to use the named routes functionality, allowing you to call the name of the route instead of the URL in router-link tags. The benefit of this is that if your routes change then you don't need to go through all the tags and change the route you just change it in your route object.

Using the above as an example we add a name to the route by adding a name property to route object.

const routes = [
    {
        path: '/',
        name: 'home',
        component: Home
    },
    {
        path: '/about',
        name: 'about',
        component: About
    },
    {
        path: '/contact',
        name: 'contact',
        component: Contact
    }
];

Now in your router-link tags you can change the routes to use the name by using the following code.

<router-link :to="{ name: 'about' }">About</router-link>

Upgrade to access all content on Paulund

Members unlock all tutorials and snippets

Access to all downloadable content

Access to code examples before others

Sign Up Now

Already a member? Login here

Subscribe To Newsletter

Get weekly updates to your email