Vue Router Redirects

Apr 24, 2020

You can configure Vue Router to redirect from one URL to another using the redirect option.

For example, the below tabbed UI has 3 links: one to /, one to /about, and one to /about-us. The /about-us link is configured to redirect to /about.

Below is the Vue Router config. Note the redirect on the /about-us path.

const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: { template: '<h1>Home</h1>' }
    },
    {
      path: '/about',
      component: { template: '<h1>About Us</h1>' }
    },
    // Note the `redirect` below.
    { path: '/about-us', redirect: '/about' }
  ]
});

Below is the actual app. Note that the router-link for the "About Us Alternate" tab points to /about-us.

const app = new Vue({
  router,
  template: `
    <div class="rendered-content">
      <div>
        <router-link to="/">Home</router-link>
        <router-link to="/about">About Us</router-link>
        <router-link to="/about-us">About Us Alternate</router-link>
      </div>
      <div class="tab-content">
        <router-view></router-view>
      </div>
    </div>
  `
}).$mount('#vue-redirect-example');

Programmatic Navigation

You can also programatically navigate using the router's push() method. The below example uses $router.push() to send the user to the /about-us URL.

const app = new Vue({
  router: router2,
  methods: {
    redirect: function(path) {
      this.$router.push({ path });
    }
  },
  template: `
    <div class="rendered-content">
      <div>
        <router-link to="/">Home</router-link>
        <router-link to="/about">About Us</router-link>
        <span @click="redirect('/about-us')">About Us Alternate</span>
      </div>
      <div class="tab-content">
        <router-view></router-view>
      </div>
    </div>
  `
}).$mount('#vue-redirect-example');

Vue School has some of our favorite Vue video courses. Their Vue.js Master Class walks you through building a real world application, and does a great job of teaching you how to integrate Vue with Firebase. Check it out!


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Vue Tutorials