https://www.npmjs.com/package/clipboard
<template>
<div>
<el-button @click="handleCommand('any string')">复制</el-button>
<button ref="copyBtn" @click="doCopy" style="display: none">copy</button>
</div>
</template>
<script>
export default {
name: 'index',
components: {},
props: {
},
data () {
return {
copyText: '',
copyBtn: null
}
},
computed: {
},
methods: {
// 复制
handleCommand (str) {
this.copyText = str
this.$refs.copyBtn.click()
},
doCopy () {
const that = this
this.copyBtn.on('success', function (e) {
that.$message.success('复制成功')
// 该成功回调:点击第一次执行一次,点击两次执行两次,点击三次执行三次...
// 所以在每次执行该回调时都重新初始化clipboard
that.initClipboard()
})
this.copyBtn.on('error', function (e) {
that.$message.error('复制失败')
})
},
initClipboard () {
this.copyBtn && this.copyBtn.destroy()
this.copyBtn = null
this.copyBtn = new this.Clipboard(this.$refs.copyBtn, {
text: () => this.copyText
})
}
},
watch: {
},
created () {
},
mounted () {
this.initClipboard()
},
beforeUpdate () {
},
updated () {
},
beforeDestroy () {
}
}
</script>