How to copy the content of an html tag to clipboard without using own function?
<div @click="navigator.clipboard.writeText(this)">Hello {{ name }}!</div>
CodePudding user response:
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.
CodePudding user response:
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>