On a regular web page we can link to other pages by using a basic anchor tag:
If you’re using Vue Router, you’ll use the special
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:
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.
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.
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:
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:
If you’re using Vue Router and you wanted to navigate to your blog, you would call
Using a relative path to simplify things:
If you have a named route you can also use that name, by passing a location object to the
Redirect to external page
If you need to navigate the user to a different website entirely, the process is almost exactly the same.
To send the user to an external page, you just have to put in a different URL:
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.
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.
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!