點燈坊

失くすものさえない今が強くなるチャンスよ

How to use window.open with Vue Route?

Sam Xiao's Avatar 2021-11-12

We often use Vue Route for all pages in Vue, but window.open only support native url. We can use resolve to transform from Vue Route to native url.

Version

Vue 3.2

window.open

route000

window.open open a window on new new tab.

<script setup>
import { useRouter } from 'vue-router'

let { resolve } = useRouter ()
let { href } = resolve ({ name: 'New' })
open (href, '_blank',)
</script>

<template>
  <div>Home</div>
</template>

Line 2

import { useRouter } from 'vue-router'

Import useRouter from vue-router.

Line 4

let { resolve } = useRouter ()

Destructure resolve from the Object returned by useRouter

LIne 5

let { href } = resolve ({ name: 'New' })

Use resolve to transform from Vue route to native url.

Line 6

open (href, '_blank',)

Use window.open to open a new window by native url.

Conclusion

  • Some API from W3C only support native url, but we can use resolve to transform from Vue route to native url