vue使用clipboard实现点击复制内容

  1. 安装clipboard
npm install clipboard -S
  1. 新建给工具类clipboard.js
import Clipboard from 'clipboard' //引入cliboard
import { Message } from 'element-ui' //引入element-ui的message提示框

function clipboardSuccess(msg) {
  Message({
    type: "success",
    message: msg||"复制成功!"
  });
}

function clipboardError(msg) {
  Message({
    type: "error",
    message: msg||"复制失败!"
  });
}

export default function handleClipboard(text, event, msg) {
  const clipboard = new Clipboard(event.target, {
    text: () => text,
  })
  clipboard.on('success', () => {
    clipboard.destroy()
    clipboardSuccess(msg)
  })
  clipboard.on('error', () => {
    clipboardError(msg)
    clipboard.destroy()
  })
  clipboard.onClick(event)
}

  1. 使用
<button @click='handleCopy("要复制的数据",$event)'>复制</button>

<script>
  import clipboard from '@/util/clipboard'
  
  handleCopy(data,event){
    clipboard(data,event);
  }
</script>  

你可能感兴趣的:(vue.js,前端,javascript)