How to redirect to another page in Vue

featured Image

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

Related Posts

featured Image

How to add common header and footer in vuejs.

Here, in this article, we will learn how to add a common header and footer component in our vuejs application. In general, we always have the same header and footer…

Read more
featured Image

How to call a function in VUE template?

Here, we will learn on how to call a function in vue template. First, we have to define the function in the methods. and then we can use an event…

Read more
featured Image

How to redirect to external url in vue

Here, we will learn how to redirect to an external URL in vuejs application. Page Navigation is one of the basic features of a website. It helps us to navigate…

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *