当前位置: 首页 > 工具软件 > Clipboard.js > 使用案例 >

clipboard.js 复制成功多次触发成功事件

鲁阳焱
2023-12-01

clipboard 文档地址

https://www.npmjs.com/package/clipboard

伪代码

<template>
  <div>
    <el-button @click="handleCommand('any string')">复制</el-button>

    <button ref="copyBtn" @click="doCopy" style="display: none">copy</button>
  </div>
</template>

<script>
export default {
  name: 'index',
  components: {},
  props: {
  },
  data () {
    return {
      copyText: '',
      copyBtn: null
    }
  },
  computed: {
  },
  methods: {
    // 复制
    handleCommand (str) {
      this.copyText = str
      this.$refs.copyBtn.click()
    },

    doCopy () {
      const that = this
      this.copyBtn.on('success', function (e) {
        that.$message.success('复制成功')
        // 该成功回调:点击第一次执行一次,点击两次执行两次,点击三次执行三次...
        // 所以在每次执行该回调时都重新初始化clipboard
        that.initClipboard()
      })
      this.copyBtn.on('error', function (e) {
        that.$message.error('复制失败')
      })
    },

    initClipboard () {
      this.copyBtn && this.copyBtn.destroy()
      this.copyBtn = null
      this.copyBtn = new this.Clipboard(this.$refs.copyBtn, {
        text: () => this.copyText
      })
    }
  },
  watch: {
  },
  created () {
  },
  mounted () {
    this.initClipboard()
  },
  beforeUpdate () {
  },
  updated () {
  },
  beforeDestroy () {
  }
}
</script>
 类似资料: