Building a Vue v2 JS app using Vue-router

Written by Mike Street on 3rd November 2016

(Last updated 30th March 2020)


Vue is a great javascript framework which I picked up to learn a couple of weeks back. I was after a simple framework which I could build an internal tool with and fortunately I came across Vue days after they released version 2. I wanted something quick, simple and (controversially for some) something that came with the ability to be executed client-side. Vue easily takes on the big names of React and Angular and has a easier learning curve for a developer new to the Javascript world of MVC (Model View Controller) apps.

This post will walk you through creating a client-side Vue JS app using Vue Router. Vue Router is a plugin for Vue which allows you to more easily add URLs and other routes to your Vue JS app. This blog assumes you have a basic knowledge of Vue.

At the end of this post, we will have an app which shows a team member list page and team member detail pages, each with their own unique URL

This tutorial uses Vue 2.0.3, Vue Router 2.0.1 and the data has been generated using JSON Generator. The data set we will be using consists of 7 people with the following attributes:

    "index": 0,
    "guid": "ebee55c4-d685-4d77-a2bb-650283fb8753",
    "picture": "",
    "age": 20,
    "eyeColor": "green",
    "name": "Hope Dennis",
    "company": "ZORK",
    "email": "",
    "address": "127 Wortman Avenue, Corriganville, Marshall Islands, 5960",
    "about": "Labore velit deserunt sunt labore nisi reprehenderit voluptate consequat laboris id minim. Elit tempor occaecat sunt enim irure aliqua eiusmod minim. Ad culpa laborum laborum anim proident duis ullamco. Sit ipsum id esse proident sunt et dolor excepteur Lorem irure anim. Lorem nisi eiusmod pariatur qui duis sint minim dolore.\r\n"

The guid attribute will be used as the URL

Loop through data

The first step is to set up our Vue app, looping through the data and outputting the name of each of our users. If you’ve used Vue before, the following should look fairly familiar:

See the Pen Vue Router - Loop through data by Liquid Light (@liquidlight) on CodePen.

The above code is looping through the data and outputting the name attribute for each user. You could chose to output other details such as the email address or company name by inserting {{ }} into the HTML code.

Create the listing component

When using Vue Router, it requires each "page" to be a Vue component. In preparation for this, let’s create a component for the user listing we've just created.

See the Pen Vue Router - Loop through data by Liquid Light (@liquidlight) on CodePen.

In the example above, I’ve made a template in the HTML using the <template> element - this is then referenced from the component using the id attribute. I found this was the neatest way of handling multi-line HTML and separating out template code from logic.

In the JS, the component has been called people-listing and includes both the template ID and declaring the props for the element. Props allow you to pass data between components - in this instance I am passing the app people array into the people-listing component. This is done by binding the prop on the HTML element (e.g. v-bind:people="people") and declaring it in the javascript component (e.g. props: ['people']) Prop are automatically declared as data, so we can start using it straight away. The component can then called using the new <people-listing v-bind:people="people" /> HTML tag.

Create the detail view component

Let’s put aside the listing component and focus on the detail view. In order to display the correct person in our template, we need to select that person from the data array and create a component to display the data.

See the Pen Vue Router - Loop through data by Liquid Light (@liquidlight) on CodePen.

For this example, I’ve hard-coded a selectedID variable in the data function so we have a GUID (the guid variable) to match and select the correct person. Notice I have replaced the <people-listing /> element in the main app HTML with <people-detail v-bind:people="people" />.

To find the correct person associated with the selectedID we utilise the filter javascript function. This returns an ID, so the first item ([0]) is returned. The item is then assigned to the person variable and passed through to the component to display it. The HTML then features displays the content required.

Setup the router

Now we have our two components, we can include Vue Router and start to display different content based on the current URL. To do this, there is some HTML and JS modifications required. First, include the Vue router javascript file:

<script src=""></script>

The next step is to replace our people-detail HTML component tag with one the router understands. Update the HTML view to the following - not forgetting to pass our people prop

<div id="app">
    <router-view class="view" :people="people"></router-view>

We now need to create a new VueRouter instance in the javascript. VueRouter accepts several arguments that need to be configured, but i’ll walk you though them:

var router = new VueRouter({
    mode: 'hash',
    base: window.location.href,
    routes: []

The three options are:

  • mode - this set’s the navigation mode. The options can be:
    • history where it users HTML5 History API to simulate different page URLs
    • hash where it places a hash in the URL before each “page” or
    • abstract works in all JavaScript environments, e.g. server-side with Node.js
  • base - The base URL of your script (in this example i’ve used a javascript variable)
  • routes - this is where we will define each of our routes (URLs or pages)

For this app, I've chosen to use the hash mode for navigation. This means we can use the window.location.href variable as the base path. If we had use history we would need to use a .htaccess file or similar to direct all our paths to a single file.

Once set up, VueRouter instance needs to be passed into our main Vue object:

var app = new Vue({
    router: router,
    data: {

Lastly, we need to slightly adjust our components to be objects assigned to a variable, rather than creating HTML elements.

For example, replace the following Vue.component call

Vue.component('people-listing', {

with a new Vue.extend method

var PeopleListing = {

We are also going to add a name attribute, to make debugging easier

name: 'PeopleListing'

Our Vue app should now look like:

See the Pen Vue Router - Loop through data by Liquid Light (@liquidlight) on CodePen.

Which may seem “broken” as it’s now not outputting any data.

Create the routes

Routes are the different URLs the app uses to display different components. Each URL needs to be defined in the routes array - including the homepage. The routes we are going to use are as follows:

  • / - A single slash signifies the homepage of the app, this is going to display our PeopleListing component
  • /:id - The colon signifies the route is variable and will be replaced with the guid in our URL - this will display the PersonDetail component

Firstly, define the route for the landing page. With this, we are going to define the URL and the Vue component to display when viewing this URL:

If you are the following to your routes array:

routes: [
    {path: '/', component: PeopleListing}

You should see your listing view component appear when viewing the page. This is telling the router to show the PeopleListing component when on the / path.

Our second route is going to define the person detail view. As we are going to use the GUID dynamically for the URL, we need to name the route. - this will all become clear in a second. Our routes array now looks like:

routes: [
  {path: '/', component: PeopleListing},
  {name: 'person', path: '/:id', component: PersonDetail}

The second route now has a name of person and includes a dynamic variable in the path.

Any links using the router need to be constructed using the router-link element. More details can be found in the router-link documentation.

For example, to link to the landing/homepage you can include the following:

<router-link to="/">Homepage</router-link>

You can go ahead and add this to your people-detail-template.

We now need to add a link to our detail page in our listing component. Update the people-listing component to include the following router-link

<li v-for="person in people">
    {{ }} 
    <router-link :to="{ name: 'person', params: { id: person.guid }}">View Details</router-link>

You’ll notice because we are passing in dynamic data, the to attribute now has a : in front of it - this is shorthand for v-bind:to. You’ll also notice instead of specifying the URL, we call the name and pass the guid through as the id.

Now when you view your page and click one of the links, you’ll find it should (hopefully) navigate to #/{guid} where {guid} is a string.

The last step is displaying the correct data at this point. You can remove the fixed selectedID from the main Vue data object and in your PersonDetail component, replace the following in your if statement this.$parent.selectedID with the parameter from the URL: this.$

Success! You now have a web app which displays data and has shareable links for each person.

View it in action on JS Bin

If you view the bin in "output" mode, you'll notice the URL changing too:

Working Vue Router example

Let me know in the comments below if you have any problems or have a better way of using the Vue router on the client side.

Edit: I have updated the blog post to use props instead of this.$parent to pass data (as is the proper way)

This article was posted in Development by Mike Street

  • Mike Street

    Mike Street

    Mike is our front-end developer who spends his days buried in CSS and Gulp. His evenings and weekends are spent tinkering with electronics and riding bikes.


hi, after looking at the examples in the repo of 2.0 - it looks like you wrote 1.0 code with 2.0.
whether it's the way you create comp instances or taking the data (calling parent instead of passing down..)
have you checked out the examples ?

Vue 2 noob11/11/2016 20:37

For search engine optimisation, does it make a difference whether you select history, hash or abstract?

Reg Cider14/11/2016 02:20

Thanks for the comment - do you have any specific examples of where i've done this? At the time of writing, there weren't too many "user friendly" tutorials out there. I'd be happy to update the blog post!

Reg - I haven't done much research and would purely depend on the type of app you are developing. If you use history, the native functionality of using the back button can be used - but if it's an app within a bigger framework or site - then hash would probably be preferable. Generally with most SEO - if it's user friendly, it's search engine friendly.

Mike Street15/11/2016 17:29

Very nice tutorial! Thank you :)

Jonas16/11/2016 17:50

To pass data from parent to child component you should be using component properties:

Franky Braem22/12/2016 13:23

Hello! Is any way to have the <templates> in separate files?
For example, people-listing-template.html and people-detail-template.html
or people-listing-template.vue and people-detail-template.vue.

Gassio20/01/2017 15:08

Thanks for the comment Jonas, I'm glad you liked it.

Gassio, there isn't natively, however there are several ways you could achieve this:

1) Load the files in with AJAX before the components get loaded
2) Include them in the HTML using PHP includes
3) Build the app server side with Node which allows components.

Mike Street24/01/2017 11:29

Thanks for this great article.
Is there any way to achieve this using vue-resource ?
I'm calling my api-fetching function when "mounted" event triggers, but Component is rendered first, so Vue's data is empty at this time , so nothing is displayed.

Guillaume09/02/2017 08:39

Thanks for this great article.
Is there any way to achieve this using vue-resource ?
I'm calling my api-fetching function when "mounted" event triggers, but Component is rendered first, so Vue's data is empty at this time , so nothing is displayed.

Guillaume09/02/2017 10:01

Hi Guillaume,

Thanks for the kind words. I have achieved this by using the fetch API on the "created" function of the Vue instance. You could also use jquery ajax if you already have that loaded.


var app = new Vue({
data: {
people: null
created: function() {
// Get data here with fetch() or $.ajax
// Assign to this.people

Mike Street14/02/2017 11:11

Thankyou so much! I found this post far more helpful in getting started than the official Vue router docs!!

Ian17/02/2017 09:51

Why is it that Vue.extend should be used instead of Vue.component?

Aran23/02/2017 16:34

Couldn't find any example without using webpack/laravel -mix. This post helped me alot, Thanks bunches!

Nima Fallah06/03/2017 22:01

Thanks for great the tut
I've tried this example on phone(locally) but it didn't work and there is no ES6 syntax in code. Do you know why is that?

Jack10/03/2017 16:14

for single .vue file component using webpack:
$ vue init webpack-simple my-project
$ cd my-project
$ npm install vue-router
$ npm install

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
import peopleListing from './people-listing.vue'
import personDetail from './person-detail.vue'

Vue.use(VueRouter, peopleListing, personDetail)

const router = new VueRouter({
{path:'/', component:peopleListing},
{name:'person', path:'/:id', component:personDetail}
new Vue({
el: '#app',
render: h => h(App)
<template>copy paste</template>
export default {
data () {
var id = @.$
var filtered = @.$parent.people.filter(λ(item) {
return (item.guid == id) ? item : false
return {person:filtered[0]}
<li v-for="person in people">
<router-link :to="{name:'person', params:{id:person.guid}}">View Details</router-link>
export default {
data () {
return {people:@.$parent.people}

<div id="app">
<router-view class="view"></router-view>
export default {
name: 'app',
data () {
return {
people:[{copy paste}]

$ npm run dev

herman sasmita12/03/2017 16:48

The data can not be displayed. Can you help me fix this issue?
<div id="app">
<li v-for="person in people">
{{ }}

var app = new Vue({
data: {
people: null
created: function() {
url: 'test.php',
this.people = JSON.parse(res);

james16/03/2017 05:40

Thanks for the comment Heman!

James: My apologies, there was a mistake in my previous code. When using ajax, you need to use "computed" values for data, not the data object itself. You can then update the data and the computed will return the updated values.

An example can be found here:

Mike Street16/03/2017 08:49

Aran: They are very similar. From my understanding Vue.extend allows you to create components without registering it as a "proper" component. (e.g. creating a <my-component> tag). Have a read over this documentation - it cleared a lot up for me:

Mike Street16/03/2017 08:57

Hi Mike! Thanks for great explanation. It's the best that i get. I just playing with your code. What if i'd like to add additional template to main route (e.g '/') ? For example, i want to add some menu on the route page sharing it with PeopleListing component... don't know how to explaine more clearly, some pseudo-code:

var app = new Vue ({
data : {
people : [{...your-people-data ...}],
menu :[{... my-menu-data same way ...}]

var Menu = Vue.extend({
template: '#my-menu-template',
data: function() {
return {
menu: this.$ //by the way - what is the $parent here ???

And <template id="my-menu-template">temlplate-code</template> in HTML which i never get on page. It's seems because routes already has a path '/' PersonDetail component. Is there any way to get more components on the same route? Or mybe where is another aprouch? Sorry if dumb question, i'm new with all of that.

Victor Pronin (1st hour with Vue)20/03/2017 21:42

Hey. I find it very helpful; there's only one thing. The links to jsbin are broken so no way to consult the code. Can you please update them?
Thank you in advance.

japer2514/01/2018 13:59

You can also create a single page application in Laravel and Vuejs without using vue-router library. Vue-router has few issues with Laravel, so it is better to do without it. Like done here:

olidev02/03/2018 11:14

Post a comment

You are currently offline. Some pages or content may fail to load.