复制功能代码
onCopy() {
const textArea = document.createElement("textarea");
textArea.value = this.content;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
return new Promise((resolve, reject) => {
document.execCommand("copy") ? resolve() : reject(new Error("出错了"));
textArea.remove();
}).then(
() => {
this.result = "复制成功";
},
() => {
this.result = "复制失败";
}
);
},
测试案例代码
<template>
<div id="app">
<div>{{ content }}</div>
<button @click="onCopy">复制内容</button>
<div>结果{{ result }}</div>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
content: "123456",
result: "",
};
},
methods: {
onCopy() {
const textArea = document.createElement("textarea");
textArea.value = this.content;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
return new Promise((resolve, reject) => {
document.execCommand("copy") ? resolve() : reject(new Error("出错了"));
textArea.remove();
}).then(
() => {
this.result = "复制成功";
},
() => {
this.result = "复制失败";
}
);
},
},
};
</script>