How to vue-router open a link in a new tab?[VUE.JS]

This is the method when you have to display it in a new tab in the environment where Vue.js is used.
However, it is easy because it is an implementation that uses JavaScript normally.
The Web API used is as follows.

Window.open()

I will explain how to use it.

Basic usage (Vue.js only OK, no Router)

// html
<button type="button" @click="linkToOtherWindow('LINK URL')">Link to new Tab</button>

// script
export default {
  methods: {
    linkToOtherWindow (url) {
      window.open(url, '_blank')
    }
  }
}

Simply pass url to window.open.
I don’t think there is any particular problem. I think the only thing you need to implement in the first place is when you need to call a method.

How to open in a new window using Vue Router

If you open it in a new window through Vue Router, it will take some time.
Use router.resolve to resolve the URL in advance.
You can also pass data with query or params .

// For profile page routing settings
const Profile= {
    template: '<div>Profile No.{{ $route.params.id }}</div>'
}
const router = new VueRouter({
  routes: [
    { path: '/profile/:id',name='profilePage', component: Profile}
  ]
})

// script Pass the resolved url to window.open
export default {
  methods: {
    linkToOtherWindow() {
      let resolvedRoute = this.$router.resolve({
        name: profilePage,
        params: {id: "someData"}
      });
      window.open(resolvedRoute.href, '_blank');
    }
  }
}

Maybe it can be used from Vue 3

<router-link :to="{ name: 'profilePage'}" target="_blank">
   LINK TO OTHER WINDOW
</router-link>

It seems that the above writing method can be done from Vue3.
How to write method, this time I tried ES6. It may get caught if it is LINTed with ES5 etc.
However, I personally think that ES6 is good enough.


Leave a Reply 0

Your email address will not be published.

5 × three =