美文网首页
vue 使用clipboard实现复制功能

vue 使用clipboard实现复制功能

作者: 哒哒哒哒da | 来源:发表于2019-12-26 15:43 被阅读0次

官网地址:https://clipboardjs.com/

下载
  npm i clipboard
引入的JS
import Vue from 'vue';
import Clipboard from 'clipboard';

function clipboardSuccess() {
  Vue.prototype.$message({
    message: '复制成功',
    type: 'success',
    duration: 1500,
  });
}

function clipboardError() {
  Vue.prototype.$message({
    message: '复制失败',
    type: 'error',
  });
}

export function handleClipboard(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', () => {
    onError ? onError() : clipboardError();
    clipboard.off('error');
    clipboard.off('success');
    clipboard.destroy();
  });
  clipboard.onClick(event);
}

html:
    <img  src="XX.png"  @click="copy('复制内容')"/>
JS:
  import {handleClipboard} from '../clipboard';
    // 复制
    copy(addr) {
      handleClipboard(
        addr,
        event,
        () => {
          this.$message.success('成功');
        },
        () => {
          this.$message.error(this.$t('失败'));
        }
      );
    },
还可以参考以下文章

https://blog.csdn.net/guxuehua/article/details/79169190
https://www.jianshu.com/p/091761ff14b1

相关文章

网友评论

      本文标题:vue 使用clipboard实现复制功能

      本文链接:https://www.haomeiwen.com/subject/xwxloctx.html