index.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. import { message } from "@/utils/message";
  2. import { useEventListener } from "@vueuse/core";
  3. import { copyTextToClipboard } from "@pureadmin/utils";
  4. import type { Directive, DirectiveBinding } from "vue";
  5. export interface CopyEl extends HTMLElement {
  6. copyValue: string;
  7. }
  8. /** 文本复制指令(默认双击复制) */
  9. export const copy: Directive = {
  10. mounted(el: CopyEl, binding: DirectiveBinding<string>) {
  11. const { value } = binding;
  12. if (value) {
  13. el.copyValue = value;
  14. const arg = binding.arg ?? "dblclick";
  15. // Register using addEventListener on mounted, and removeEventListener automatically on unmounted
  16. useEventListener(el, arg, () => {
  17. const success = copyTextToClipboard(el.copyValue);
  18. success
  19. ? message("复制成功", { type: "success" })
  20. : message("复制失败", { type: "error" });
  21. });
  22. } else {
  23. throw new Error(
  24. '[Directive: copy]: need value! Like v-copy="modelValue"'
  25. );
  26. }
  27. },
  28. updated(el: CopyEl, binding: DirectiveBinding) {
  29. el.copyValue = binding.value;
  30. }
  31. };