NOTE | Vue — How to redirect to external URL

There’s an external link on my Vue page, like www.google.com, I want to redirect to this URL after clicking it.
However, it doesn’t work by using <router-link>
<router-link to="www.google.com" target="_blank">
www.google.com
</router-link>
And the URL of the new tab will become
http://localhost:8080/#/www.google.com
Method 1
Well, Vue router doesn’t work in different domain, if you want to redirect to another domain, you need to use <a> tag:
<a href="https://www.google.com" target="_blank">
www.google.com
</a>
Method 2
Or try the following way, add an event handler:
// HTML
<button @click.stop.prevent="onClick">www.google.com</button>// JS
methods: {
onClick() { window.location.href = 'https://www.google.com' // original tab
window.open('https://www.google.com', '_blank') // open new tab },
}
Method 3
Or you want to redirect to an external URL by heading for another component:
<template>
<div class="about">
<ul>
<li>
<h3> Redirect while create </h3>
</li>
</ul>
</div>
</template>
You have to add the following code inside the created()
lifecyle hook:
created() {
window.location.href = 'https://google.com'
}
Method 4
Or go to router/index.js and add the following code inside the route
object by using the beforeEnter
route guard:
beforeEnter(to, from, next) {
window.location.href = 'https://google.com'
}
Basic tools & settings
- Vue 2.6.11
- Vue CLI: 4.1.1
- Vue router 3.5.1
- Vue router mode: hash mode
REPO & DEMO
Reference
- Stack Overflow — VueJs vue-router linking an external website
- Reactgo — How to redirect to external URL in Vue