由于异步请求 不能直接拿到文本内容,所以第一次复制的时候是空的
讲下思路,就是新增一个按钮,按钮的真正功能是复制已请求到的文本内容,通过模拟点击复制到剪贴板。
下面是代码:
<el-button @click="getLink(row.id)" >链接</el-button>
<el-button ref="copy" class="btn" :data-clipboard-text="linkUrl" @click="copyLink" style="opacity:0;width:1px">
<!-- 真正复制链接的按钮 --></el-button>
getLink(id){
let me = this;
this.$http(me.url+'link-page/url', {
method: 'GET',
params:{linkPageId:id}
}).then(function(response) {
console.log(response.data.data,id)
me.linkUrl = response.data.data+id
me.$forceUpdate()
setTimeout(()=>{//模拟点击真正复制链接的按钮
me.$refs.copy.$el.click();
},10)
});
},
// 复制链接方法
copyLink () {
var clipboard = new Clipboard('.btn');
clipboard.on('success', e => {
this.$message({
message:'已复制链接',
type:'success'
})
clipboard.destroy() // 使用destroy可以清楚缓存
})
clipboard.on('error', e => {
this.$message({
message:'复制失败',
type:'error'
})
clipboard.destroy()
})
},