copy 指令

80 阅读1分钟
/**
 * v-copy
 * 复制某个值至剪贴板
 * 接收参数:string类型/Ref<string>类型/Reactive<string>类型
 */
 import type { Directive, DirectiveBinding } from "vue";
 import { ElMessage } from "element-plus";

 interface ElType extends HTMLElement {
    copyData: string | number;
    __handleClick__: any;
 }

 const copy: Directive = {
  // 在绑定元素的 attribute 前
  // 或事件监听器应用前调用
  created(el, binding, vnode, prevVnode) {
    // 下面会介绍各个参数的细节
  },
  // 在元素被插入到 DOM 前调用
  beforeMount() {},
  // 在绑定元素的父组件
  // 及他自己的所有子节点都挂载完成后调用
  mounted(el: ElType, binding: DirectiveBinding) {
    el.copyData = binding.value;
    el.addEventListener("click", handleClick);
  },
  // 绑定元素的父组件更新前调用
  beforeUpdate() {},
  // 在绑定元素的父组件
  // 及他自己的所有子节点都更新后调用
  updated(el: ElType, binding: DirectiveBinding) {
    el.copyData = binding.value;
  },
  // 绑定元素的父组件卸载前调用
  beforeUnmount(el: ElType) {
    el.removeEventListener("click", el.__handleClick__);
  },
  // 绑定元素的父组件卸载后调用
  unmounted() {}
 }

  function handleClick(this: any) {
    const input = document.createElement("input");
    input.value = this.copyData.toLocaleString();
    document.body.appendChild(input);
    input.select();
    document.execCommand( "Copy", false);
    document.body.removeChild(input);
    ElMessage({
      type: "success",
      message: "复制成功"
    });
  }

 export default copy;