Here in this short post, we will learn how you can redirect a user from one page URL to another using vue-router.

In Vue, routing is done through the use of vue-router package. It enables us to perform single-page routing within our Vue application with ease.

You get the option to add vue-router to your vue project when you first create the app using vue CLI.

redirect to another page in Vue

If you haven't, then you can install it manually using the npm command in the terminal:

npm install vue-router@4

Once it is added to your project, we can use the redirect property to redirect the routes in Vue.

Redirect to a different page in Vue

In vue, all the routes are configured in the router's config file located in /src/router/index.js file.

So, whenever you create a new route, you have to declare it in the router config file.

Now, let's see how you can first create two routes and then redirect one URL to another page URL using the router config file.

Let's create two pages, home and about page first.

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

Now you can use the redirect option to redirect a user from about page to home page like this.

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

Here, we have redirect users from /about to '/' (Home page) .

We can also redirect using the named route:

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

Related Topics:

How to add 404 page in Vue using vue-router

How to redirect to external URL in vue

How To Open Link in a New Tab in Vue?

Set URL Query Params In Vue Using Vue-Router


💾 Recommended Articles