原文转载自添加链接描述
<template>
<div>
<div v-clickCopy>1234566666: 点我直接复制文本</div>
</div>
</template>
<script>
export default {
data() {
return {
}
},
directives: {
clickCopy: {
inserted(el, binding,vnode) {
console.log(el, binding);
el.addEventListener('click', () => handleClick(el.innerText))
el.style.cursor = 'copy'
function handleClick(text) {
// 创建元素
if (!document.getElementById('copyTarget')) {
const copyTarget = document.createElement('input')
copyTarget.setAttribute('style', 'position:fixed;top:0;left:0;opacity:0;z-index:-1000;')
copyTarget.setAttribute('id', 'copyTarget')
document.body.appendChild(copyTarget)
}
// 复制内容
const input = document.getElementById('copyTarget')
input.value = text
input.select()
document.execCommand('copy')
/* vue 自定义指令内部没有this指向 可以传vnode.context解决 */
const that = vnode.context
that.$message.success('恭喜');
setTimeout(() => {
that.showSuccess()
}, 500);
}
}
}
},
methods: {
showSuccess(){
this.$message('恭喜复制成功');
}
}
}
</script>
<style>
</style>