1、安装引用
npm install clipboard --save
2、在main.js全局注册
import clipboard from 'clipboard'
// 注册到vue原型上
Vue.prototype.clipboard = clipboard
3、在要使用的vue组件中引用如下,我在copy方法中加了一个3s的延时是因为,提示用户复制成功的弹窗默认展示3s,防止用户多次点击,一定一定要在成功后销毁clipboard实例,否则会出现随着点击次数增加,弹窗数增加的bug
<template>
<div>
<p>{{wechat}}</p>
<button class="cobyOrderSn" data-clipboard-action="copy" :data-clipboard-text="wechat" @click="copy" :disabled="disabled">复制</button>
</div>
</template>
<script>
export default {
data () {
return {
disabled: false,
wechat:'这是复制的内容'
}
},
methods: {
// 复制功能
copy () {
const _this = this
var clipboard = new this.clipboard('.cobyOrderSn')
clipboard.on('success', function (val) {
_this.disabled = true
setTimeout(() => {
_this.disabled = false
// 销毁实例防止多次触发
clipboard.destroy()
}, 3000)
_this.$message({
message: '复制成功',
type: 'success'
})
})
clipboard.on('error', function () {
_this.$message.error('复制失败,请手动复制')
})
}
}
}
</script>