import useClipboard from 'vue-clipboard3'

/**
 * v-copy 复制指令
 * @example v-copy="'要复制的文本'"
 * @example v-copy="dynamicText"
 */
export default {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const clipboardAttr = 'data-clipboard-text'
    el.setAttribute(clipboardAttr, binding.value)
    const { toClipboard } = useClipboard()
    el.onclick = () => {
      toClipboard(el.getAttribute(clipboardAttr)!)
        .then(() => {
          ElMessage.success('复制成功')
        })
        .catch(() => {
          ElMessage.error('复制失败')
        })
    }
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    const clipboardAttr = 'data-clipboard-text'
    el.setAttribute(clipboardAttr, binding.value)
  }
}
