记录一下点击按钮复制内容的实现。
实现效果如图:

复制成功后Ctrl+v可粘贴:

实现方式也比较简单:
<template>
<div>
<p>{{ myText }}</p>
<el-button plain @click="handleCopy">复制</el-button>
</div>
</template>
<script>
export default {
name: 'index',
data () {
return {
myText: '不管明天会不会更好,至少我拥有此刻啊。'
}
},
methods: {
handleCopy () {
try {
const input = document.createElement("input");
input.value = this.myText;
document.body.appendChild(input);
input.select();
if (document.execCommand('Copy')) this.$message.success('复制成功');
else { this.$message.error('复制失败'); }
document.body.removeChild(input);
} catch (err) {
this.$message.error('error');
}
}
}
}
</script>
document.execCommand(‘Copy’):拷贝当前选中的内容到剪切板,但document.execCommand已被弃用,谨慎选用,参见(https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand)
本文介绍了如何在Vue应用中实现点击按钮复制文本功能,包括使用`document.execCommand`方法,以及注意事项,由于`document.execCommand`已弃用,提供了相关替代链接。
127

被折叠的 条评论
为什么被折叠?



