How to redirect to external url in vue

š Table Of Content
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 through the web pages and also to other websites.
Normally we use a anchor tag <a href="www.mysite.com/about">
to navigate from one page to another.
In Vuejs, since we use Vue-Router, we use <router-link to="www.mysite.com/about">
to move from one page to another in our Vue application.
Normally, to redirect a user from one page to a different in the same site, we use the this.$router.push
method:
this.$router.push("/about");
However , to direct a user to a different external URL, we will use window.location.href
property.
window.location.href = "https://www.google.com/"
Note: The
window.location
object can be use to get current page address and also to redirect the browser to different pages / sites.
Redirect to external URL in Vuejs
In this example, we have a /about
route in our vue app and when an user visits that route, we will programmatically redirect him / her to 'www.google.com' domain.
To redirect the user, we will use the window.location.href
object.
And to redirect to external url programmitically, we will use the created()
lifecycle hook and beforeEnter
Ā route guard.
Using created() lifecycle hook
We will added the code window.location.href = "https://www.google.com/"
inside the created()
lifecycle hook function. So once the route request is fetch, it will redirect the user to the external url before the DOM is rendered or mounted.
<template>
<div class="main-container">
<h1>About Page</h1>
</div>
</template>
<script>
export default {
created() {
window.location.href = "https://www.google.com/";
},
};
</script>
Using beforeEnterĀ route guard
Using route guard is very easy and simple, just add the external URL inside the route's configuration object with beforeEnter
route guard.
Example:
{
path: "/about",
component: About,
beforeEnter(to, from, next) {
window.location.href = "https://www.google.com/";
}
}
Now whenever the user visit the /about
route, the router guard will check the beforeEnter
guard and redirect the user to google.com.
Learn more about Vue Router and its usages here : https://router.vuejs.org/guide/
Related Topics:
Set URL Query Params In Vue Using Vue-Router
How To Remove Hashbang (#) From URL In Vue?