Can vue-router open a link in a new tab?

后端 未结 11 1680
礼貌的吻别
礼貌的吻别 2020-12-04 16:58

I have a summary page and a detail subpage. All of the routes are implemented with vue-router (v 0.7.x) using programmatic navigation like this:



        
相关标签:
11条回答
  • 2020-12-04 17:56

    I think that you can do something like this:

    let routeData = this.$router.resolve({name: 'routeName', query: {data: "someData"}});
    window.open(routeData.href, '_blank');
    

    it worked for me. thanks.

    0 讨论(0)
  • 2020-12-04 17:57

    For those who are wondering the answer is no. See related issue on github.

    Q: Can vue-router open link in new tab progammaticaly

    A: No. use a normal link.

    0 讨论(0)
  • 2020-12-04 17:57

    This works for me:

    In HTML template: <a target="_blank" :href="url" @click.stop>your_name</a>

    In mounted(): this.url = `${window.location.origin}/your_page_name`;

    0 讨论(0)
  • 2020-12-04 17:59

    Somewhere in your project, typically main.js or router.js

    import Router from 'vue-router'
    
    Router.prototype.open = function (routeObject) {
      const {href} = this.resolve(routeObject)
      window.open(href, '_blank')
    }
    

    In your component:

    <div @click="$router.open({name: 'User', params: {ID: 123}})">Open in new tab</div>
    
    0 讨论(0)
  • 2020-12-04 18:05

    If you are interested ONLY on relative paths like: /dashboard, /about etc, See other answers.

    If you want to open an absolute path like: https://www.google.com to a new tab, you have to know that Vue Router is NOT meant to handle those.

    However, they seems to consider that as a feature-request. #1280. But until they do that,



    Here is a little trick you can do to handle external links with vue-router.

    • Go to the router configuration (probably router.js) and add this code:
    /* Vue Router is not meant to handle absolute urls. */
    /* So whenever we want to deal with those, we can use this.$router.absUrl(url) */
    Router.prototype.absUrl = function(url, newTab = true) {
      const link = document.createElement('a')
      link.href = url
      link.target = newTab ? '_blank' : ''
      if (newTab) link.rel = 'noopener noreferrer' // IMPORTANT to add this
      link.click()
    }
    

    Now, whenever we deal with absolute URLs we have a solution. For example to open google to a new tab

    this.$router.absUrl('https://www.google.com)
    

    Remember that whenever we open another page to a new tab we MUST use noopener noreferrer.

    Read more here

    or Here

    0 讨论(0)
提交回复
热议问题