Open router link in a new tab in Vue

vuejs2 min read

Learn how to open router-link or external url links in a new tab / window in Vuejs

This is a short article on how to open router-link in a new tab or, a new browser window in VueJS.

In Vue, to navigate between different pages we use the <router-link> component with its to="" attribute.

Example

<router-link to="/about">About</router-link>

This code will take us from a specific page to the /about page within the same browser tab.

Open Link in a New Tab

However, if we want to open the /about page in a new tab, then we have to add a target attribute with _blank as a value in our <router-link> component.

<router-link to="/about" target="_blank">About</router-link>

Programatically, we can navigate a page and open it in a new tab using the $router instance.

Example:

<template> <div id="app"> <button @click="aboutPage()">About</button> </div> </template> <script> export default { methods: { aboutPage() { let route = this.$router.resolve({ path: "/about" }); window.open(route.href); }, }, }; </script>

In the above code, we have used this.$router.resolve() and window.open() method.

The resolve() method returns the normalized version of the route location. It includes a href property that we can use with the window.open() method to open the page in a new tab of the browser.

Open External Link in a New Tab In Vue

In VueJs, to open an external link in a new tab, we can use the HTML anchor tag <a> and then pass the target attribute and set the value to _black.

<template> <div id="app"> <a href="https://en.wikipedia.org/" target="_blank">Wikipedia</a> </div> </template>

In Vue, we can also open the external link in a new tab using programmatic navigation like this:

<template> <div id="app"> <button @click="gotoWiki()">Go To Wikipedia</button> </div> </template> <script> export default { methods: { gotoWiki() { window.open("https://en.wikipedia.org/", "_blank"); }, }, }; </script>

Related Topics:

Set URL Query Params In Vue Using Vue-Router

How To Redirect To External Url In Vue

Get the name of the current route in Vue

Related Posts