Open router link in a new tab in Vue


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.

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 page 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 and also gives the href property.

and window.open() method is used to open a new browserย window or new tab.

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 with _black as the value in your template.

<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 name of the current route in Vue


๐Ÿ’พ Recommended Articles