Open router link in a new tab in Vue
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
Related Posts
Easy Way to use localStorage with Vue
Short article on how to use local storage with Vue and learn saving and storing data in local storage with the setItem() and getItem() methods.
Force update Vue to Reload/Rerender component
Short tutorial on how to correctly force update Vue.js component to reload or rerender. The component is reinitialized without having to do a browser refresh.
Set and get cookies in a browser in Vue App
Find out how to set and get cookies in a browser for your webpage in Vue using vue-cookies package.
Save vuex state after page refresh in Vue App
Short tutorial on how to save (or persist) data in a vue application using Vuex and vuex-persist npm package.
