npm i clipboard
<el-button
size="mini"
icon="el-icon-edit"
class="tag"
@click="handleCpoy(scope.row, '.tag')"
>复制</el-button
>
import Clipboard from 'clipboard'
handleCpoy(row, type) {
let msg = row.msg
// 复制
let clipboard = new Clipboard(type, {
text: function () {
//需要复制的文本
return msg;
},
});
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();
});
},
// 原生方法
const save = function (e) {
e.clipboardData.setData("text/plain", msg);
e.preventDefault(); // 阻止默认行为
};
// once 表示 listener 在添加之后最多只调用一次。如果是 true, listener 会在其被调用之后自动移除
const once = {
once: true,
};
document.addEventListener("copy", save,once); // 添加一个copy事件,当触发时执行一次,执行完删除
document.execCommand("copy"); // 执行copy方法
this.$message({ message: "复制成功", type: "success" });
}
vue clipboard复制文本到剪切板
于 2022-11-20 17:16:49 首次发布