解决vue复制插件clipboard.js点击两次才能复制成功的问题


封装clipboard.js:

import Clipboard from "clipboard"
import Vue from "vue"

function clipboardSuccess() {
  Vue.prototype.$message.success("复制成功")
}

function clipboardError() {
  Vue.prototype.$message.error("复制失败")
}

export function copy(text, event, onSuccess, onError) {
  event = event || {}
  const clipboard = new Clipboard(event.target, {
    text: () => text
  })
  clipboard.on('success', () => {
    onSuccess ? onSuccess() : clipboardSuccess()
    clipboard.off('error')
    clipboard.off('success')
    clipboard.destroy()
  })
  clipboard.on('error', () => {
    onSuccess ? onError() : clipboardError()
    clipboard.off('error')
    clipboard.off('success')
    clipboard.destroy()
  })
  clipboard.onClick(event)
}

只需要增加 clipboard.onClick(event) 这行代码就行了,网上很多办法都写的乱七八糟的。

在vue文件中只需要引入封装好的js文件进行调用就可以了。

<i class="el-icon-copy-document" @click="handleCopy(alertTitle,$event)"></i>

import { copy } from "@/utils/clipboard";

handleCopy(text, e) {
  copy(text, e);
},

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM