Can vue-router open a link in a new tab?
Vue.js doesn't include a built-in vue-router command for opening a new tab. However, you can attain this by using a regular <a> tag coupled with Vue's binding. Simply bind the href
to the URL you want to target and set target="_blank"
. The code snippet you're searching for might look like this:
Here, computedUrl
is the computed property that yields the URL string. This code allows your link to open in another tab in line with HTML rules, taking advantage of Vue's reactivity for the URL.
Navigating to a new tab programmatically
In case you need to open a new tab programmatically based on some logical conditions, you would need to surpass the hurdles of href
. While Vue Router doesn’t directly provide this function, we can use a combination of this.$router.resolve
and window.open
to get it done.
If you are working with the Composition API, using the useRouter
hook gets you access to the router instance, similar to how this.$router
works for Options API. Here’s what that looks like:
And here's the Composition API conversion:
Use this method by calling it with the route name and parameters to open the desired route in a new tab.
Extending the Vue Router prototype
If you want to go an extra mile, you can extend Vue Router's prototype to create an open
method. Here's how you can do that:
This can be invoked in the components using @click="$router.open({ name: 'routeName' })"
.
Kindly note, these methods are workarounds as Vue Router does not natively support opening new tabs programmatically. Keep an eye out for discussions on the GitHub issues page for any updates or good practices.
Using <router-link> for new tabs without JS
Since Vue Router 3.0.1, you can conveniently use <router-link>
coupled with target="_blank"
attribute for new tab opening that aligns with Vue Router's navigations. Here's how to implement this:
This mode of navigation sticks to Vue's declarative nature and preserves HTML semantics, allowing for a more accessible solution minus additional JavaScript.
Roadblocks and considerations
Be aware of popup blockers that are a part of modern browsers. If users have blocked popups for your domain, the new tab may not open.
Another scenario to consider is client-side navigation. In case you're opening a Vue app route in a new tab, it's crucial to ensure the state in that app is independently set or properly initialized to avoid weird behavior.
Was this article helpful?