0

How to copy the content of an html tag to clipboard without using own function?

<div @click="navigator.clipboard.writeText(this)">Hello {{ name }}!</div>
DevonDahon
  • 7,460
  • 6
  • 69
  • 114

3 Answers3

1

I think in Vue3 that is not possible without 'ugly' solutions, see here for inspiration. But I think the cleanest way is to just create a method with that one line of code in it.

Gabe
  • 2,168
  • 2
  • 4
  • 16
1

As per the document, Universal code cannot assume access to platform-specific APIs, so if your code directly uses browser-only globals like window or document, they will throw errors. Hence, the common approach is to lazily access them inside client-only lifecycle hooks such as mounted.

Live Demo :

new Vue({
  el: '#app',
  data: {
    name: 'Alpha',
    browserApi: null
  },
  mounted() {
    this.browserApi = navigator
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div ref="elText" @click="browserApi.clipboard.writeText($refs.elText.innerText)">Hello {{ name }}!</div>
</div>
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
0

better for readability

Vue;

new Vue({
  el: '#app',
  data: {
    name: 'Alpha',
  },
  methods {
    copyPageUrl(){
        navigator.clipboard.writeText($refs.elText.innerText)
    },
  }
})

Html;

<div id="app">
  <div ref="elText" @click="copyPageUrl">Hello {{ name }}!</div>
</div>