On a regular web page we can link to other pages by using a basic anchor tag:

<a href="www.google.com">Google</a>

If you're using Vue Router, you'll use the special RouterLink component:

<RouterLink :to="www.google.com">Google</RouterLink>

But what if you want to redirect programmatically, without using an anchor tag at all?

If you're using Vue Router you'll push the new URL onto the router in order to do a redirect: this.$router.push('www.yoursite.com/blog').

In this short article we'll cover how to redirect to internal and external pages, if you're using Vue Router and if you're just using plain Vue.

Redirect to internal page

First we'll cover how to do this with plain Vue, and then we'll get into how this can be done if you're using Vue Router.

Plain Vue

Let's say you want to navigate the app to the url https://www.yoursite.com/blog. If you want to redirect programmatically you need to use the browser's API for this:

window.location.href = 'https://www.yoursite.com/blog';

You can also use just a relative path, which is better because it will only change what comes after the first /. This way if your hostname changes you don't need to update anything in your code:

window.location.href = 'blog';

Vue Router

If you're using Vue Router and you wanted to navigate to your blog, you would call this.$router.push:

this.$router.push('www.yoursite.com/blog');

Using a relative path to simplify things:

this.$router.push('blog');

If you have a named route you can also use that name, by passing a location object to the push method:

// Named route
const router = new VueRouter({
  routes: [
    {
      path: '/blog',
      name: 'blog',
      component: Blog,
    }
  ]
});
// Navigating to the named route
this.$router.push({ name: 'blog' });

Redirect to external page

If you need to navigate the user to a different website entirely, the process is almost exactly the same.

Plain Vue

To send the user to an external page, you just have to put in a different URL:

window.location.href = 'https://www.google.com';

But now relative paths won't work at all, because you're not navigating on the same site. You have to include the new hostname as well.

Vue Router

If you're using Vue Router, you'll still have to use window.location.href if you want to navigate to an external page. This is because Vue Router only works in your Vue app, and can't take the user outside of the app.

Conclusion

You can dig deeper into all of the options that Vue Router gives you by reading their detailed guide.

It goes into everything you could possibly need, and explains it all very clearly. Definitely worth reading!