编写一个指令(v-el-table-clipboard)使el-table-column在show-overflow-tooltip 情况下点击复制

编写一个指令(v-el-table-clipboard)使el-table-column在show-overflow-tooltip 情况下点击复制_第1张图片

使用方法

  • el-table绑定指令
  • 在需要的复制的column中传入**class-name=“copy-prop”**即能实现复制效果
<el-table v-el-table-clipboard:copy v-el-table-clipboard:success="() => $message.success('复制成功')">
  <el-table-column class-name="copy-prop" label="xxx" show-overflow-tooltip />
  // 通过插槽形式
  <el-table-column label="xxx">
    <template slot-scope="scope">
      <span class="copy-prop">{{ xxx }}</span>
    </template>
  </el-table-column>
</el-table>

v-el-table-clipboard

import Clipboard from 'clipboard'
export default {
  bind(el, binding) {
    switch (binding.arg) {
      case 'success':
        el._vClipBoard_success = binding.value;
        break;
      case 'error':
        el._vClipBoard_error = binding.value;
        break;
      default: {
        el.onClickListener = bindEvent(el, binding);
        el.addEventListener('click', el.onClickListener, true);
      }
    }
  },
  update(el, binding) {
    if (!el._vClipboard) return;
    if (binding.arg === 'success') {
      el._vClipBoard_success = binding.value;
    } else if (binding.arg === 'error') {
      el._vClipBoard_error = binding.value;
    } else {
      el._vClipBoard.text = function () { return binding.value; };
      el._vClipBoard.action = () => binding.arg === 'cut' ? 'cut' : 'copy';
    }
  },
  unbind(el, binding) {
    if (!el._vClipboard) return
    if (binding.arg === 'success') {
      delete el._vClipBoard_success;
    } else if (binding.arg === 'error') {
      delete el._vClipBoard_error;
    } else {
      el._vClipBoard.destroy();
      delete el._vClipBoard;
    }
    el.removeEventListener('click', el.onClickListener);
  }
}
function bindEvent(el, binding) {
  return function onClickListener(evt) {
    const _target = evt.target || evt.srcElement;
    const parent = _target.parentNode;
    if (!_target) return;
    if (parent.className.includes('copy-prop') || _target.className.includes('copy-prop') && parent.innerText.length) {
      const clipboard = new Clipboard(_target, { text: () => _target.innerText, action: () => binding.arg === 'cut' ? 'cut' : 'copy' });
      clipboard.on('success', e => {
        const callback = el._vClipBoard_success;
        callback && callback(e);
        el._vClipBoard.destroy();
      });
      clipboard.on('error', e => {
        const callback = el._vClipBoard_error;
        callback && callback(e);
        el._vClipBoard.destroy();
      });
      el._vClipBoard = clipboard;
    }
  }
}

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