How to Redirect and Alias with Vue Router?

Estimated read time 2 min read

Vue Router is a popular routing library for Vue.js applications that allows you to create and manage routes in your Vue.js applications. You can use Vue Router to redirect and alias routes to provide a smooth navigation experience for your users. Here’s how you can do it:

  1. Redirecting Routes: You can use the redirect option in Vue Router to redirect one route to another. The redirect option takes a path as a value and redirects the user to that path when the original path is accessed. Here’s an example:
// router.js

import Vue from 'vue';
import Router from 'vue-router';
import Home from './views/Home.vue';
import About from './views/About.vue';

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/about',
      name: 'about',
      component: About
    },
    // Redirect /about-us to /about
    {
      path: '/about-us',
      redirect: '/about'
    }
  ]
});

In this example, when the user accesses the /about-us route, they will be redirected to the /about route.

  1. Aliasing Routes: You can use the alias option in Vue Router to create an alias for a route. The alias option takes a path as a value and creates an alias for that path. Aliased routes are treated as separate routes, but they display the same content as the original route. Here’s an example:
// router.js

import Vue from 'vue';
import Router from 'vue-router';
import Home from './views/Home.vue';
import Contact from './views/Contact.vue';

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/contact',
      name: 'contact',
      component: Contact
    },
    // Alias /contact-us to /contact
    {
      path: '/contact-us',
      component: Contact,
      alias: '/contact'
    }
  ]
});

In this example, both the /contact and /contact-us routes will display the same content from the Contact.vue component.

Note that the redirect and alias options in Vue Router can be used in combination with other options and features such as route parameters, nested routes, and route guards to create complex navigation and routing logic in your Vue.js applications.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply