If the paste copy function is implemented in the project, there are currently three methods on the market, all of which have advantages and disadvantages. You can choose according to the actual situation of your project. This section will describe these three methods in detail, focusing on the third method.
1. Project requirements diagram display:
1. Install third-party plug-ins (not recommended)
This method is very compatible and is not recommended if the project is only used once.
Install the plugin
npm install clipboard --save
复制代码
Introduce plugins
import Clipboard from 'clipboard';
复制代码
used in the project
<template>
<span class="copy" @click="onCopy">
<i class="iconfont iconcopy"></i>
<span>点击复制</span>
</span>
</template>
<script>
methods: {
onCopy(){
let clipboard = new Clipboard('.copy')
clipboard.on('success', e => {
console.log('复制成功')
// 释放内存
clipboard.destroy()
})
clipboard.on('error', e => {
// 不支持复制
console.log('该浏览器不支持自动复制')
// 释放内存
clipboard.destroy()
})
}
}
</script>
复制代码
2. The browser comes with the Document.execCommand() copy method (not recommended)
Although this method does not require installation of plug-ins, the official website states as follows:
used in the project
<script>
methods: {
onCopy(){
//创建一个input框
const input = document.createElement("input")
//将指定的DOM节点添加到body的末尾
document.body.appendChild(input)
//设置input框的value值为直播地址
input.setAttribute("value", e)
//选取文本域中的内容
input.select()
//copy的意思是拷贝当前选中内容到剪贴板
//document.execCommand()方法操纵可编辑内容区域的元素
//返回值为一个Boolean,如果是 false 则表示操作不被支持或未被启用
if (document.execCommand("copy")) {
document.execCommand("copy")
}
//删除这个节点
document.body.removeChild(input)
}
</script>
复制代码
3. Clipboard.writeText method (highly recommended)
illustrate
Clipboard
The methods of the interface writeText()
can write a specific string to the clipboard of the operating system. will return one Promise
, which will be parsed once the contents of the clipboard are updated. If the caller does not have permission to write to the clipboard, deny writing to the clipboard (reject)
used in the project
onCopy() {
navigator.clipboard.writeText(this.detailData.clientSecret).then(() => {
this.$message.success('复制成功')
})
}
复制代码