Guide to Vue Router Redirects

Introduction

When developing web applications with Vue.js that have many pages and incorporate many features such as logging in, authentication, carting, as well as a good deal of CRUD applications, we will need to implement routing at some point, which involves redirecting a user from one page to another either programmatically or when they access a route via the URL.

In this article, we will learn the various means of redirecting and routing in Vue.js with practical code samples.

Prerequisite

Routing in Vue.js is accomplished through the use of the vue-router package, which enables us to easily perform single page routing within our Vue application. To implement router redirects in Vue, we must first install this package in our project, which we can do by running the following command in our terminal:

$ npm install vue-router@4

Redirect with Vue

All routes in Vue.js are configured in the router's configuration file, which is a dedicated file for all types of routing in Vue. This file is usually found under /src/router/index.js.

To use a route, we have to declare it in the router configuration file, after which we can reference it in other parts of the application. Routing can be done in a variety of ways, and different scenarios may necessitate different redirects, but let's start with the most basic type of redirect before moving on to others such as programmatic, conditional, and error redirects.

When a user navigates to the /home route, say it should always redirect them to the / route, thereby showing the HomePage. This can be done via redirects:

const routes = [
   {
      path: '/',
      name: 'Home',
      component: HomePage,
   },
   {
      path: '/home',
      redirect: '/',
   }
];

The main emphasis is on the second object which takes in the path and redirect options, when a user navigates to the set path it automatically redirects them to the path set in the redirect option.

Note: We will notice that the redirect actually replaces the link, meaning when we navigate to /home the URL switches to / thereby showing the component set for the / route.

In a situation where we don’t want the URL to change, but we want it to show the component set for the / route, then we can make use of an Alias.

Alias

An alias is an option we can add an alias for an existing route. In effect, we can have multiple routes that work with a particular component, rather than redirecting to a single route that handles it.

For example, when we set an alias to /home and the actual path is set to / with a component of HomePage, when a user navigates to /home the HomePage component will appear, but the URL remains /home:

{
   path: '/',
   name: 'Home',
   component: HomePage,
   alias: '/home',
},

Note: An alias can take an array of more than one path and these paths can include parameters.

{
   path: '/',
   name: 'Home',
   component: HomePage,
   alias: ['/home', '/homepage'],
},

Now - /, /home and /homepage all actually handle the same HomePage component!

Redirect Programmatically

We can also perform programmatic redirects, such as when a button is clicked or an action is performed. This is handled the router's push() method, which can be used anywhere in our application. When the button is clicked in the example below, it takes the user to the specified path:

<template>
   <h2>Home Page</h2>
   <button @click="$router.push('/about')">Redirect Me</button>
</template>

This can also be handled within our script tag using the this keyword:

<template>
   <h2>Home Page</h2>
   <button @click="redirectMe()">Redirect Me</button>
</template>

<script>
   export default {
      methods: {
         redirectMe() {
            this.$router.push('/about');
         },
      },
   };
</script>

It’s important to note that the argument could be a string path as we used earlier or a location descriptor object which could accept name, path, etc.:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

// String path
$router.push('/about')

// Descriptor object with path
$router.push({ path: '/about' })

// Named route 
$router.push({ name: 'About' })

Replacing The Current URL

As we navigate using programmatic methods, we're pushing and adding to our browser's history just as the user would through manual clicking. If we want to push without creating a new history entry - we'll want to replace the entry:

router.push({ path: '/about', replace: true })
// This is equivalent to
router.replace({ path: '/about' })

Conditional Redirect

We may want to redirect users when a specific command is completed, such as when we want to authenticate a user, confirm a product purchase, and so on. This is typically accomplished through the use of conditional statements, such as:

<template>
   <h2>Home Page</h2>
   <button @click="checkUser()">Authenticate Me</button>
</template>

<script>
   export default {
      data(){
         return{
            isLoggedIn: true,
         }
      },
      methods: {
         checkUser() {
            if(this.isLoggedIn){
               this.$router.push('/dashboard');
            }else{
               this.$router.push('/login');
            }
         },
      },
   };
</script>

We can also perform this without having to create a method:

<template>
   <h2>Home Page</h2>
   <button @click="{ isLoggedIn ? $router.push('/dashboard') : $router.push('/login'); }">
      Authenticate Me
   </button>
</template>

<script>
   export default {
      data() {
         return {
            isLoggedIn: true,
         };
      },
   };
</script>

Redirect to a 404 Page

Finally, it would be beneficial to include how to handle errors when a user navigates to the incorrect route. When a user navigates to a route that is not declared in our router's configuration file, it displays an empty component, which is typically not the desired behavior.

This is easily handled in by catching all routes except those configured with a regular expression and assigning them to an error component:

{
   path: '/:catchAll(.*)',
   name: 'ErrorPage',
   component: ErrorPage
}

Conclusion

In this article, we learned how to redirect in Vue and how to handle redirects in various ways.

Last Updated: June 13th, 2022
Was this article helpful?

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms