需求:项目中有一链接地址,点击按钮,将该链接内容复制。
<el-button size="small" type="primary" @click.stop="copyAddress">
复制地址
</el-button>
方法1:
copyAddress() {
let copyInput = document.createElement("input"); // 创建元素
// 这边为链接地址this.liveLink = 'www.baidu.com'
copyInput.value = this.liveLink;
document.body.appendChild(copyInput); // 添加元素
copyInput.select();
// console.log(copyInput.value);
document.execCommand("Copy"); // 执行浏览器复制命令
document.body.removeChild(copyInput); // 移除刚创建的元素
this.$message.success("复制成功");
},
方法2:
methods: {
copyAddress(val) {
var copyInput = document.createElement("input"); // 创建元素
//val是要复制的内容
copyInput.setAttribute("value", val);
document.body.appendChild(copyInput);
copyInput.select();
try {
var copyed = document.execCommand("copy");
if (copyed) {
document.body.removeChild(copyInput);
this.$Message.success("复制成功");
}
} catch {
this.$Message.error("复制失败,请检查浏览器兼容");
}
},
},