Anthony

Adding Routing to a Vue.js cli App

Adding Routing to a Vue.js cli App

Vue.js is a great JavaScript Framework with a nice and simple architecture. And the router being one of it’s coolest features (my opinion though). Just in case you didn’t know, Vue-Router is a Vue.js plugin to add routing to your application. In other words, it’s the part that makes the URL change when you click something in the page, and helps to show the correct view when you hit a specific URL.

However, if you choose not to install routing when first creating your project (vue create project), and you later change your mind, and then decided to add the vue-router. It could sometime be a pain in the ass, when you try to do the setup manually.

So in this article, I’ll show you how to add Vue.js routers to your existing Vue.js application.

Getting started

installing the Vue Router.

 npm install vue-router
         or
 yarn add vue-router

In your Vue.js src folder, create a router.js file then import Vue and Vue-router:

import Vue from 'vue'
import Router from 'vue-router'

//Use Router
Vue.use(Router)

Import your components (router.js)

import Vue from 'vue'
import Router from 'vue-router'

//Import Components
import Home from './components/Home.vue'
import About from './components/About.vue'

Vue.use(Router)

We have to configure the routers to make them work. The router method takes an Array of objects which in turn takes each component’s properties: (router.js)

Vue.use(Router)

export default new Router({
    routes:[
        {
            path: '/',
            name: 'home',
            component: Home
        },
        {
            path: '/about',
            name: 'about',
            component: About
        }
    ]
})

We’re done with router.js , now go to your main.js file and import the vue-router.

 import router from './router'

In that same main.js file you should see a config like this:

  new Vue({
    render: h => h(App),
  }).$mount('#app')

To make the routing work add the router, like this:

  new Vue({
    router,
    render: h => h(App),
  }).$mount('#app')

Use Routers

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

Conclusion

In most cases you would’nt have to do this if you started the vue project with the cli and you tick of the vue-router option, but if you did’nt do that then you’ll have to do the setup manually.

Is there anything I missed in this post? Share it with me on twitter

comments powered by Disqus