How to Implement Routing in Vue.js

Vue is already an excellent Javascript library that allows you to create dynamic frontend applications. Vue.js is also great for single-page applications (SPA).  Vue Router is the official router for Vue.js.

It profoundly integrates with Vue.js core to make building Single Page Applications with Vue.js a breeze. Features include:

  1. Nested route/view mapping.
  2. It is a modular, component-based router configuration.
  3. Route params, query, wildcards.
  4. View transition effects powered by Vue.js’ transition system.
  5. It has a fine-grained navigation control.
  6. It links with automatic active CSS classes.
  7. It has HTML5 history mode or hash mode, with auto-fallback in IE9.
  8. It has customizable Scroll Behavior.

Here are the steps to implement routing in Vue.js.

Step 1: Install Vue Router

Although we can install the vue-router by default while creating a new project, let me install it separately for you so we can integrate it on our own.

npm install vue-router --save

You can import the router inside the Vue.js application. So let us import inside the src >> main.js file.

// main.js

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

Vue.use(VueRouter)

Step 2: Basic Routing with Vue.js

Inside the src folder, create one file called routes.js and add the following code.

// routes.js

const routes = [];

export default routes;

In the future, we will define the routes inside this file. Now, we need to import this routes.js file inside the main.js file.

// main.js

import Vue from 'vue';
import App from './App.vue';
import VueRouter from 'vue-router';

import routes from './routes';

Vue.config.productionTip = false;

Vue.use(VueRouter);

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

We passed the router object while creating a vue instance.

Step 3: Create Vue components

The next step is to create three new components inside the src >> components folder.

  1. Home.vue
  2. Register.vue
  3. Login.vue
// Home.vue

<template>
    <div>
        Home
    </div>
</template>
<script>
export default {
    
}
</script>
// Register.vue

<template>
    <div>
        Register
    </div>
</template>
<script>
export default {
    
}
</script>
// Login.vue

<template>
    <div>
        Login
    </div>
</template>
<script>
export default {
    
}
</script>

Import all the components inside the src >> routes.js file. Next, we will define the routes for each component.

// routes.js

import Home from './components/Home.vue';
import Register from './components/Register.vue';
import Login from './components/Login.vue';

const routes = [
    { path: '/', component: Home },
    { path: '/register', component: Register },
    { path: '/login', component: Login },
];

export default routes;

The next step is to create a VueRouter instance and pass the routes object. So, we need to import the routes.js file inside the main.js file.

// main.js

import Vue from 'vue';
import App from './App.vue';
import VueRouter from 'vue-router';

import routes from './routes';

Vue.config.productionTip = false;

Vue.use(VueRouter);

const router = new VueRouter({routes});

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

We need to display the routing components based on the routes. So we can do that by adding the <router-view> component. So let us add that inside the src >> App.vue file.

// App.vue

<template>
  <div id="app">
    <nav>
        <router-link to='/'>Home</router-link>
        <router-link to='/register'>Register</router-link>
        <router-link to='/login'>Login</router-link>
    </nav>
    <router-view />
  </div>
</template>

<script>
export default {
}
</script>

Save this file, go to the terminal, and start the vue development server.

npm run serve

Go to http://localhost:8080, and your URL changes to this: http://localhost:8080/#, and it will render the Home component. 

We have used Hash routing, which is popular in building a Single Page Application(SPA).

Vue HTML 5 History Mode Routing

We are using the hash mode of routing. We can also use HTML 5 History Mode. By default, vue.js uses the hash mode. Therefore, we must tell the vue application externally to do the history routing.

We need to modify one line of code inside the main.js file, and we are done.

// main.js

const router = new VueRouter({mode: 'history', routes});

Now, we can route the components without the hash.

Dynamic routing in Vue.js

The above example shows the views based on the URL, handling the //register, and routes.

We can achieve the dynamic segment. The above are static segments.

Let us define one more route inside the src >> routes.js called /student/:id and create a component inside the src >> components folder called Student.vue.

// Student.vue

<template>
    <div>
        Student
    </div>
</template>
<script>
export default {
    
}
</script>

Import the component inside the routes.js file and register that component.

// main.js

import Home from './components/Home.vue';
import Register from './components/Register.vue';
import Login from './components/Login.vue';
import Student from './components/Student.vue';

const routes = [
    { path: '/', component: Home },
    { path: '/register', component: Register },
    { path: '/login', component: Login },
    { path: '/student/:id', component: Student },
];

export default routes;

Inside the student route component, we can reference the route using the $route and access the id using $route.params.id. So, write the following code inside the Student.vue file.

// Student.vue

<template>
    <div>
        Student ID is: {{ $route.params.id }}
    </div>
</template>
<script>
export default {
    
}
</script>

After you call Vue.use() method inside the main.js file,  passing the router object in any component of the app, you have access to these objects:

  1. this.$router:  which is the router object.
  2. this.$route:  which is the current route object.

Vue Router Object

We can access the router object using this.$router from any component when a Vue Router is installed in the root Vue component, and it offers many nice features.

We can make the app navigate to a new route using

this.$router.push()
this.$router.replace()
this.$router.go()

If you have previously performed the CRUD operations using Vue.js as a frontend, we have used the push() method to change the route programmatically.

Named routes in Vue.js

We can simplify the linking process of navigating different routes by defining the named or designated routes.

Sometimes it is more convenient to identify the route with the name, especially when linking to the route or performing navigations. You can name the route in the routes options while creating a Router instance. Now, we will add one property called name to the routes object in a routes.js file.

// routes.js

const routes = [
    { path: '/', component: Home, name: 'home' },
    { path: '/register', component: Register, name: 'register' },
    { path: '/login', component: Login, name: 'login' },
    { path: '/student/:id', component: Student, name: 'student' },
];

We can change the links inside the navbar in the App.vue file.

// App.vue

<template>
  <div id="app">
    <nav>
        <ul>
            <li>
                <router-link :to="{name: 'home'}">Home</router-link>
            </li>
            <li>
                <router-link :to="{name: 'register'}">Register</router-link>
            </li>
            <li>
                <router-link :to="{name: 'login'}">Login</router-link>
            </li>
            <li>
                <router-link :to="{name: 'student', params: {id: 2}}">Student</router-link>
            </li>
        </ul>
    </nav>
    <router-view />
  </div>
</template>

<script>
export default {
}
</script>

 

How To Use Routing in VueJS

Redirecting Programmatically in Vue Router

In the single-page application, we often face a situation where we need to redirect after some successful operations.

We can redirect the route programmatically using the router object. For example, when the user successfully logs in, we must programmatically redirect to the home route.

Let us see the following example.

Let us create one more component called Redirect.vue inside the components folder and add the following code.

// Redirect.vue

<template>
    <div></div>
</template>
<script>
export default {
    mounted() {
        this.$router.push('/home');
    }
}
</script>

When the component is mounted, we redirect the page to the Home component.

Import this component inside the routes.js file and register.

// main.js

import Home from './components/Home.vue';
import Register from './components/Register.vue';
import Login from './components/Login.vue';
import Student from './components/Student.vue';
import Redirect from './components/Redirect.vue';

const routes = [
    { path: '/', component: Home, name: 'home' },
    { path: '/register', component: Register, name: 'register' },
    { path: '/login', component: Login, name: 'login' },
    { path: '/student/:id', component: Student, name: 'student' },
    { path: '/redirect', component: Redirect, name: 'redirect' },
];

export default routes;

Go to this URL: http://localhost:8080/redirect and see that we are redirecting to the Home component.

Navigating Router History with Go Method

Sometimes, we must go forward and backward programmatically using navigating history routing. So, let us take an example of a 4o4 page. Create a component inside the components folder called 404.vue and add the following code.

// 404.vue

<template>
    <div>
        Whoops 404!! The page is not available.
        <a href="#" @click.prevent="back">Go back</a>
    </div>
</template>
<script>
export default {
    methods: {
        back() {
            this.$router.go(-1);
        }
    }
}
</script>

Here, we defined the 404 page and then put the link redirecting to the previous route.

Import inside the routes.js file.

// routes.js

import Home from './components/Home.vue';
import Register from './components/Register.vue';
import Login from './components/Login.vue';
import Student from './components/Student.vue';
import Redirect from './components/Redirect.vue';
import Error from './components/404.vue';

const routes = [
    { path: '/', component: Home, name: 'home' },
    { path: '/register', component: Register, name: 'register' },
    { path: '/login', component: Login, name: 'login' },
    { path: '/student/:id', component: Student, name: 'student' },
    { path: '/redirect', component: Redirect, name: 'redirect' },
    { path: '/404', component: Error, name: '404' },
];

export default routes;

Go to http://localhost:8080/404, and you can see the link to the previous page.

Click that link, and you will go to the last page. So it is working and programmatically.

That’s it.

16 thoughts on “How to Implement Routing in Vue.js”

  1. Hello. Thank you for this useful tutorial on VueJS with Laravel. I’ve followed your steps but am having issue with this.$router.push(). Home component loads when the page is mounted. But when I click on any of the routes, I end up having two components. One on top of another. I need your help with this. Thank you

    Reply
    • I got the same issue, and after checking his example you can see that he has the same problem. So if you fixed it. plz let me know thank a lot.

      Reply
  2. I can not express how happy I was to just land in this page and follow the steps of this tutorial and see that everything just…WORKED… you know?

    thank so much why is it so difficult to find nice and complete tutorials like this

    if this was stack overflow I would create 437 accounts just to upvote your answer

    god bless u good night thanks

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.