基于clipboard简单封装一个全局使用的文本复制组件
[ 2021/08/06, Vue , 6941阅, 0评 ]

使用之前别忘了先安装clipboard(npm i clipboard -S

1、调用方法

this.$store.commit('emitCopy', '复制内容')

2、App.vue文件中

<template>
  <div class="app-root">
    <router-view />
    <!-- 复制面板 -->
    <ClipboardPanel ref="clipboardRef" />
  </div>
</template>
<script>
import ClipboardPanel from '@/components/ClipboardPanel.vue'
export default {
  name: 'App',
  components: {
    ClipboardPanel,
  },
  watch: {
    '$store.state.copyText'(val) {
      const text = val.replace(/\d{13}#/, '')
      this.$refs['clipboardRef'].doCopy(text)
    },
  },
}
</script>

3、store文件中

export default new Vuex.Store({
  state: {
    copyText: '',
  },
  mutations: {
    emitCopy(state, payload) {
      state.copyText = `${Date.now()}#${payload}`
    },
  },
})

4、ClipboardPanel组件内容如下

<template>
  <div
    ref="copyRef"
    id="tempCopyFlag"
    style="display: none"
    :data-clipboard-text="tempText"
    @click="handleCopy('#tempCopyFlag')"
  ></div>
</template>
<script>
import Clipboard from 'clipboard'
export default {
  name: 'ClipboardPanel',
  data() {
    return {
      tempText: '',
    }
  },
  methods: {
    handleCopy(dom) {
      const clipboard = new Clipboard(dom)
      clipboard.on('success', (e) => {
        this.$toast({
          message: '复制成功',
          duration: 1500,
        })
        clipboard.destroy()
      })
      clipboard.on('error', (e) => {
        clipboard.destroy()
      })
    },
    doCopy(text) {
      this.tempText = text
      this.$nextTick(() => {
        this.$refs['copyRef'].click()
      })
    },
  },
}
</script>

有朋自远方来...评论一下呗O(∩_∩)O