复制方法是开发中经常会用到的,在实现最近一个需求的时候发现了差异,常用的复制方法对不可复制内容无效,最终实现了功能,在此列出方法,记录一下
常用可粘贴内容的复制方法:
copyHandle(name, data) { // 复制短链接
const text = this.$refs[`${name}`]
text.value = data
text.select()
document.execCommand('copy')
this.$message({
message: '复制成功!',
type: 'success'
})
},
试了navigator.clipboard方法也可实现,但navigator对象不同页面包含的对象有差异,所以不是很推荐
navigator.clipboard.writeText(data).then(() => {
this.$message({
message: '复制成功!',
type: 'success'
})
})
不可复制内容复制
方法一:创建一个隐藏可编辑内容实现(较为笨拙)
function copyTextToClipboard(text) {
// 创建一个临时的输入框
const textArea = document.createElement("textarea");
// 隐藏输入框
textArea.style.position = "fixed";
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.width = "2em";
textArea.style.height = "2em";
textArea.style.padding = "0";
textArea.style.border = "none";
textArea.style.outline = "none";
textArea.style.boxShadow = "none";
textArea.style.background = "transparent";
// 设置输入框内容
textArea.value = text;
// 将输入框添加到页面
document.body.appendChild(textArea);
// 选中输入框内容
textArea.select();
textArea.setSelectionRange(0, text.length);
// 执行复制命令
let successful = false;
try {
successful = document.execCommand('copy');
} catch (err) {
console.error('Oops, unable to copy', err);
}
// 移除输入框
document.body.removeChild(textArea);
return successful;
}
// 使用示例
const textToCopy = "Hello, world!";
copyTextToClipboard(textToCopy);
方法二: 使用clipboard.js
<el-button type="primary" size="mini" class="tag" @click="copyHandle(info.text)">复制链接</el-button>
import Clipboard from 'clipboard'
copyHandle (data) {
let clipboard = new Clipboard('.tag', {
text: function () {
return data
}
})
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()
})
},