1.原生方法:
如下方法,可以实现浏览器的复制文本功能,但是因为execCommand已经被放弃,但是还没执行,好像在ios15之后,ios不支持了,导致,ios上无法复制。
copyWord(word){
const textArea = document.createElement('textArea')
textArea.value = word;
//添加到dom节点中
textArea.style.width = 0
textArea.style.position = 'fixed'
textArea.style.left = '-999px'
textArea.style.top = '10px'
textArea.setAttribute('readonly', 'readonly')
document.body.appendChild(textArea)
textArea.select()
document.execCommand('copy')
// 移除元素
document.body.removeChild(textArea);
}
2.引用组件
运行
npm install --save vue-clipboard2
在main.js中引用
import VueClipboard from 'vue-clipboard2'
Vue.use(VueClipboard)
使用方法:
this.$copyText(res.data?.data?.url || '').then((e) => {
this.$toast.success('复制链接成功');
}, (e) => {
this.$toast.error('复制链接失败');
})```
首先需要使用vue-clipboard2实现的功能是:复制通过后台得到的数据,vue-clipboard2在安卓和pc端都没有问题,但是到了ios系统,不管是safari,微信,都会没有效果。
查阅了一下资料说是因为this.$copyText()写在axios这个异步方法里,而vue-clipboard2主页上说这个方法不可以写在异步方法里。
解决办法是给this.$copyText()外面包一个定时器,代码如下:
setTimeout(()=>{
this.KaTeX parse error: Expected '}', got 'EOF' at end of input: … this.toast.success(‘复制链接成功’);
}, (e) => {
this.$toast.error(‘复制链接失败’);
})
},100)
成功解决了这个问题!
最后提一句,本来我是使用原生的document.execCommand("copy")来实现复制的。
[参考链接:](https://blog.csdn.net/weixin_43299180/article/details/112473038)
[参考链接:](https://juejin.cn/post/7129718241726824461)