How to Setup Routes with Vuejs

In this tutorial I will show you how to set up routes with one of my favorite a JavaScript library Vue.js.  Vuejs is very similar library like angularjs but with more simple and flexible api.

So let’s start.

For this tutorial I will use Official vue router plugin which you can grab from its official github repository https://github.com/vuejs/vue-router.  Make sure that you setup your playground like this.

For this tutorial we will place our JavaScript code in separate file called app.js

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue Router Tutorial</title>
    <!-- Let's call bootstrap for little styling -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-default navbar-static-top">
            <div class="container">
                <div class="navbar-header">
                    <a class="navbar-brand">Vue Router Example</a>
                </div>
                <div id="navbar" class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li><a v-link="{ path: '/' }">Dashboard</a></li>
                        <li><a v-link="{ path: '/about' }">About</a></li>
                        <li><a v-link="{ path: '/contact' }">Contact</a></li>
                        <li><a v-link="{ path: '/404' }">404</a></li>
                    </ul>
                </div>
            </div>
        </nav>
        <div class="container">          
            <router-view></router-view>       
        </div>
    </div>
    <!-- Vuejs Library -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.12.10/vue.min.js"></script>
    <!-- Vue Router Plugin -->
    <script src="https://cdn.rawgit.com/vuejs/vue-router/dev/dist/vue-router.min.js"></script>
    <!-- Out custom Javascript Code -->
    <script src="app.js"></script>
</body>
</html>

 

And our app.js file will look like this

/**
 * Define your components
 */

// For 404 page
var notFound = Vue.extend({
   template: '<h1>Not Found</h1>'
})

// For dashboard. This is our root page
var dashboardComponent = Vue.extend({

    // You can use also use template path (Thanks to @jcerdan)
    // path : '/path/to/component.html'

    template: 
            '<div class="jumbotron">' + 
                '<h1>Dashboard</h1>' +
                '<p>This is dashboard</p>' +
                '<p>' +
                    '<a v-link="{ path: '/subroute' }" class="btn btn-lg btn-primary" role="button">View SubRoute</a>' +
                '</p>' +
            '</div>' +
            // To show nested subroute
            '<router-view></router-view>'
})

// About page.
var aboutComponent = Vue.extend({
   template: 
        '<div class="jumbotron">' +
            '<h1>About</h1>' +
            '<p>This is about page</p>' +
            '<p>' +
                '<a v-link="{ path: '/about/subroute' }" class="btn btn-lg btn-primary" role="button">View SubRoute</a>' +
            '</p>' +
        '</div>' +
        '<router-view></router-view>'
})

// Our subroute content.
var subRouteContent = Vue.extend({
   template: 
        '<h1>Navbar example</h1>' +
        '<p>This example is a quick exercise to illustrate how the default, static and fixed to top navbar work. It includes the responsive CSS and HTML, so it also adapts to your viewport and device.</p>' +
        '<p>To see the difference between static and fixed top navbars, just scroll.</p>'
})

// Contact page content
var contactComponent = Vue.extend({
   template: 
            '<div class="jumbotron">' +
                '<h1>Contact</h1>' +
                '<p>This is contact page</p>' +
            '</div>'
})

// Tell Vue to use view-router
Vue.use(VueRouter)

// Router options
var router = new VueRouter({
   history: false,
   root: '/'
})

// Router map for defining components
router.map({
   // For Not Found template (404)
   '*': {
      component: notFound
   },

   '/': {
      component: dashboardComponent,
      
      // Defining Subroutes
      subRoutes: {
      '/subroute': {
           component: subRouteContent
         }
      }
   },

   '/about': {
      component: aboutComponent,
      subRoutes: {
      '/subroute': {
           component: subRouteContent
         }
      }
   },

   '/contact': {
      component: contactComponent
   }
});

var App = Vue.extend()

router.start(App, '#app')

 

Here is working demo!

See the Pen Basic Vue Router Example by Swapnil Bhavsar (@IamSwap) on CodePen.0

For more information on Vue Route, refer it’s online documentation on github.

  • jcerdan

    Hi,

    Nice job! Everything in a clear example. That’s good.

    Do you know an easy way to separate component into files (html/css/js)? If template is complex, it’s really molest to write into a string.
    That’s the only thing that blocks me in using vuejs.

    best

    • Swapnil Bhavsar

      Yes, you can separate components in files with VueJs. You will need to define component name in router.map.

      router.map({
      ‘/url’: {
      // Define your component name here
      component: myComponent
      }
      })

      And in “myComponent.js” you can define your component.

      var myComponent = Vue.extend({
      // Or you can use template: require(‘/path/to/component.html’)
      template:
      ” +
      ‘This is Foo!’ +
      ” + // <- nested outlet
      '’
      })

      Please let me know if this works for you.

      • jcerdan

        Hi,

        That’s not exactly what I meant. In your component:

        var mycomponent = Vue.extend({
        template:
        ‘…’ +
        ‘…’ +
        …;
        })

        can the ‘template’ param be taken from an outside html file? This way, for routing purposes, it’s easier, as putting a lot of HTML code inside the template param is not “beatiful”.

        best

        • Swapnil Bhavsar

          yes you can define external html file like this.

          template: require(‘/path/to/component.html’)

          I have already shown it in code comments. 😉

          Let me know if you need further help. 🙂

          • jcerdan

            Hi,

            no. that does not work.
            You should use { path: ‘/’ } into v-link directive also as if not your example does not work also.

            best,

          • Swapnil Bhavsar

            Sorry my mistake. I was using old version vue-router. I have updated the example. Check it out.

            Thanks for pointing it out. 🙂

          • jcerdan

            Hi

            I manage to do it but you need to compile files with browserify. You should add this to the comments at least.

            best,

  • jcerdan

    Hi,

    Nice job! Everything in a clear example. That’s good.

    Do you know an easy way to separate component into files (html/css/js)? If template is complex, it’s really molest to write into a string.
    That’s the only thing that blocks me in using vuejs.

    best

    • Swapnil Bhavsar

      Yes, you can separate components in files with VueJs. You will need to define component name in router.map.

      router.map({
      ‘/url’: {
      // Define your component name here
      component: myComponent
      }
      })

      And in “myComponent.js” you can define your component.

      var myComponent = Vue.extend({
      // Or you can use template: require(‘/path/to/component.html’)
      template:
      ” +
      ‘This is Foo!’ +
      ” + // <- nested outlet
      '’
      })

      Please let me know if this works for you.

      • jcerdan

        Hi,

        That’s not exactly what I meant. In your component:

        var mycomponent = Vue.extend({
        template:
        ‘…’ +
        ‘…’ +
        …;
        })

        can the ‘template’ param be taken from an outside html file? This way, for routing purposes, it’s easier, as putting a lot of HTML code inside the template param is not “beatiful”.

        best

        • Swapnil Bhavsar

          yes you can external html file like this.

          template: require(‘/path/to/component.html’)

          I have already shown it in code comments. 😉

          Let me know if you need further help. 🙂

          • jcerdan

            Hi,

            no. that does not work.
            You should use { path: ‘/’ } into v-link directive also as if not your example does not work also.

            best,

          • Swapnil Bhavsar

            Sorry my mistake. I was using old version vue-router. I have updated the example. Check it out.

            Thanks for pointing it out. 🙂

          • jcerdan

            Hi

            I manage to do it but you need to compile files with browserify. You should add this to the comments at least.

            best,

  • Markus Smet

    Hey nice article, am just wondering how you made the nav context aware? So when you click on the navigation, it applies a ‘bold’ effect to the text so you know where you are? I want to do that and can’t see how you did it in your code pen example?

  • Leandro

    would be great a updated code with vuejs 2, and if not too much with syntax highliting