前端实现一键复制

222 阅读1分钟

使用Clipboard前端插件

更多功能需要去官网发掘

    <el-button @click="copy('复制文本',$event)">复制</el-button>
    npm install clipboard -S
    
    import Clipboard from 'clipboard'
    import Vue from 'vue'
    function copy(text, event){
        const clipboard = new Clipboard(event.target, {
            text: () => text
        })
        clipboard.on('success', () => {
            Vue.prototype.$message({message:'success',type:'success'})
            clipboard.destroy()
        })
        clipboard.on('error', () => {
            Vue.prototype.$message({message:'error',type:'error'})
            clipboard.destroy()
        })
        clipboard.onClick(event)
    }

使用浏览器api

  1. 复制:execCommand('copy')
  2. 剪切:execCommand('cut')
  3. 粘贴:execCommand('paste')
    copy() {
        const transfer = document.createElement('input');
        document.body.appendChild(transfer);
        transfer.value = ''; // 这里表示想要复制的内容
        transfer.focus();    // input聚焦
        transfer.select();   // input内容选择
        // 使用方法进行对选择的文本进行复制
        if (document.execCommand('copy')) {
          document.execCommand('copy');
        }
        transfer.blur();     // input失焦
        this.$message({
          message: '复制成功!',
          type: 'success',
        });
        document.body.removeChild(transfer);
      }