原理:创建input
DOM节点再删除该节点,调用 document.execCommand("Copy");
方法
应用:当我们需要一个点击事件把 文本内容 复制到剪切板的时候,只需要在自己定义在工具类.js 文件中,引用一下就行,我定义在tool.js中
src/utils/tool.js 中定义
// 复制内容到剪切板, 成功返回true
export function copyString(string){
if(!string) return false
let dom = document.createElement('input');
dom.value = string;
document.body.appendChild(dom);
dom.select(); // 选择对象
document.execCommand("Copy"); // 执行浏览器复制命令
document.body.removeChild(dom)
Message.success('内容已经复制到剪切板')
return true
}
index.vue中使用
<template>
<div>
<button @click="copyUrl('www.baidu.com')">复制地址</button>
</div>
</template>
<script>
import { copyString } from 'src/utils/tool.js'
export default {
methods: {
copyUrl(url){
let flag = copyString(url)
... 通过返回值 flag 判断接下来的操作
}
}
}
</script>