Redirecting to Another Page Using Vue and Javascript

To utilize router redirects in Vue, you must first install the package in your project. This can be accomplished by running the command below in your terminal:
Redirect with Vue
In order to use it in your code, you must import both Vue and Vue Router. This is why you are receiving the error “router is not defined at eval” in your method. The router’s configuration file is a dedicated file for all types of routing in Vue, where all routes are set up.

Introduction

In the process of building Vue.js web applications that are feature-rich and have multiple pages, including logging in, authentication, carting, and CRUD applications, routing becomes essential. This requires redirecting users from one page to another, either programmatically or when they access a specific route through the URL.

This write-up will provide practical code examples on the different ways of redirecting and routing in Vue.js.

Prerequisite

Vue.js implements routing by utilizing the

vue-router

package. This package allows for seamless single page routing within our Vue application. Prior to implementing router redirects in Vue, we need to install this package in our project. We can achieve this by executing the following command in our terminal.

$ npm install [email protected]
Redirect with Vue

The router’s configuration file is where all types of routing in Vue are set up, including all routes. This dedicated file is typically located at

/src/router/index.js

.

In order to make use of a route, it must first be declared in the router configuration file. Once declared, the route can be utilized throughout other areas of the application. While routing can be accomplished in a multitude of ways, various situations may require distinct redirects. However, it’s best to begin with the simplest form of redirect before examining other types such as programmatic, conditional, and error redirects.

If a user visits the

/home

path, they should be redirected to the

/

path to display the

HomePage

content. This redirection can be accomplished using redirects.

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

The primary focus is on the second object that accepts both

path

and

redirect

options. Whenever users access the designated

path

location, they are automatically redirected to the path that is specified in the

redirect

option.

It should be noted that the redirect replaces the link, resulting in a switch of the URL when navigating to

/home

to

/

. This switch displays the component set for the

/

route.

To display the component assigned to the

/

route without altering the URL, an Alias can be utilized.

Alias

A possible addition to a route is to designate an

alias

as an alternate name for it. This allows for the existence of multiple routes that utilize the same component, instead of relying solely on a single route to manage it.

By assigning an alias to

/home

and setting the path to

/

that contains a

HomePage

component, users can navigate to

/home

and view the

HomePage

component without any change in the URL, which remains as

/home

.

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

Please keep in mind that an

alias

has the ability to accept an array of multiple paths, which may also contain parameters.

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

The three components,

/

,

/home

, and

/homepage

, all deal with the identical

HomePage

element.

Redirect Programmatically

In addition to manual navigation, programmatic redirects can also be implemented through actions such as button clicks. These redirects are managed by the

push()

method of the router, which can be utilized throughout the entire application. For instance, clicking a button in the following example will direct the user to the designated path.


It is possible to manage this using the

this

keyword in the script tag.


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

It’s worth mentioning that the argument can either be a string path similar to the one we previously used, or a location descriptor object that can accommodate name, path, and other parameters.

Free eBook: Git Essentials

Discover our practical and interactive Git tutorial, complete with industry-approved norms, recommended techniques, and a useful cheat sheet. End your reliance on Google for Git commands and start acquiring knowledge!

// String path
$router.push('/about')
// Descriptor object with path
$router.push({ path: '/about' })
// Named route 
$router.push({ name: 'About' })

Replacing The Current URL

When we use programmatic methods for navigation, we are essentially simulating the user’s manual clicking behavior. In order to avoid creating a new history entry, we can opt to replace the existing one by pushing it.

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

Conditional Redirect

Conditional statements are usually utilized to redirect users after completing a particular command, for instance, when we require user authentication or confirmation of a product purchase.


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

It is possible to execute this task without the need to generate a method.


<script>
   export default {
      data() {
         return {
            isLoggedIn: true,
         };
      },
   };
script>
Redirect to a 404 Page

It would be advantageous to provide instructions on managing errors when a user accesses an incorrect route, as the current outcome of displaying an empty component is usually undesirable.

One way to efficiently manage this is by capturing all routes, except for those that are set up with a regular expression, and directing them to an error component.

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

Conclusion

This article has taught us about Vue redirection techniques and ways to manage redirects effectively.

Frequently Asked Questions