记录一下解决vue-clipboard2在ios复制没有效果

1,822 阅读1分钟
携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第1天,点击查看活动详情
首先需要使用vue-clipboard2实现的功能是:复制通过后台得到的数据,vue-clipboard2在安卓和pc端都没有问题,但是到了ios系统,不管是safari,微信,都会没有效果,代码图片如下:

1.jpg

查阅了一下资料说是因为this.$copyText()写在axios这个异步方法里,而vue-clipboard2主页上说这个方法不可以写在异步方法里。

Yes, you can do it by using our new method: this.$copyText. See sample2, where we replace the clipboard directives with a v-on directive.

Modern browsers have some limitations like that you can't use window.open without a user interaction. So there's the same restriction on copying things! Test it before you use it. Make sure you are not using this method inside any async method.

所以我的解决办法是给this.$copyText()外面包一个定时器,代码如下:

2.jpg

成功解决了这个问题!

最后提一句,本来我是使用原生的document.execCommand("copy")来实现复制的 虽然document.execCommand("copy")已经明确被指出即将废弃(但不还是没有废除吗.),一开始不管在安卓,pc还是ios都是可以实现复制功能的。但是突然有一天功能在ios失效了,排查了一下发现ios15.5还可以用,但是另一位同事ios版本更新到15.6功能就失效了(当然是不是真的是这个原因就不知道了),因为ios15.6是刚出的版本,所以网上也没有找到相应的资料...

        input.value = this.link;
        input.select(); // 选中文本
        document.execCommand("copy")
        this.$message({
          message: '复制成功',
          type: 'success'
        });

然后就换了方式使用vue-clipboard2vue-clipboard2还是挺好用的,npm下载,然后在main.js中引入,就可以直接使用this.$copyText()实现复制功能了

npm install --save vue-clipboard2
import VueClipborad from 'vue-clipboard2'
Vue.use(VueClipborad)