cnpm install clipboard --save-dev
import clipboard from 'clipboard';
Vue.prototype.clipboard = clipboard;
<el-button @click="copy(categoryCode)" id="getCategoryCode">复制</el-button>
copy (data) {
let clipboard = new this.clipboard('#getCategoryCode', {
text: function () {
return data
}
})
clipboard.on('success', e => {
this.$message({message: '复制成功', showClose: true, type: 'success'})
clipboard.destroy()
})
clipboard.on('error', e => {
this.$message({message: '复制失败,', showClose: true, type: 'error'})
clipboard.destroy()
})
},
上面是直接实用的方式
下面是我写的指令方式复制
cnpm install clipboard --save-dev // 安装依赖
import clipboard from 'clipboard'; // main.js 引入
Vue.directive('copy', { // 自定义指令copy
bind(el, bingind, vnode) {
let copy = new clipboard(el, {
text: function () {
return JSON.stringify(bingind.value)
}
});
copy.on('success', e => {
alerts('复制成功', 'success') // 自己写的弹框
})
copy.on('error', e => {
alerts('复制失败,', 'error') // 自己写的弹框
})
}
});
<el-button v-copy="params">复制</el-button> // 页面中使用 params是要复制的内容
或者
import clipboard from 'clipboard';
Vue.directive('copy', {
bind(el, bingind, vnode) {
const copy = new clipboard(el);
el.dataset.clipboardText = JSON.stringify(bingind.value)
copy.on('success', e => {
alerts('复制成功', 'success') // 自己写的弹框
});
copy.on('error', e => {
alerts('复制失败,', 'error') // 自己写的弹框
});
},
update(el, bingind) {
el.dataset.clipboardText = JSON.stringify(bingind.value)
}
});