useCopyModal.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { isRef, unref, watch, Ref, ComputedRef } from 'vue';
  2. import Clipboard from 'clipboard';
  3. import { ModalOptionsEx, useMessage } from '/@/hooks/web/useMessage';
  4. /** 带复制按钮的弹窗 */
  5. interface IOptions extends ModalOptionsEx {
  6. // 要复制的文本,可以是一个 ref 对象,动态更新
  7. copyText: string | Ref<string> | ComputedRef<string>;
  8. }
  9. const COPY_CLASS = 'copy-this-text';
  10. const CLIPBOARD_TEXT = 'data-clipboard-text';
  11. export function useCopyModal() {
  12. return { createCopyModal };
  13. }
  14. const { createMessage, createConfirm } = useMessage();
  15. /** 创建复制弹窗 */
  16. function createCopyModal(options: Partial<IOptions>) {
  17. let modal = createConfirm({
  18. ...options,
  19. iconType: options.iconType ?? 'info',
  20. width: options.width ?? 500,
  21. title: options.title ?? '复制',
  22. maskClosable: options.maskClosable ?? true,
  23. okText: options.okText ?? '复制',
  24. okButtonProps: {
  25. ...options.okButtonProps,
  26. class: COPY_CLASS,
  27. [CLIPBOARD_TEXT]: unref(options.copyText),
  28. } as any,
  29. onOk() {
  30. return new Promise((resolve: any) => {
  31. const clipboard = new Clipboard('.' + COPY_CLASS);
  32. clipboard.on('success', () => {
  33. clipboard.destroy();
  34. createMessage.success('复制成功');
  35. resolve();
  36. });
  37. clipboard.on('error', () => {
  38. createMessage.error('该浏览器不支持自动复制');
  39. clipboard.destroy();
  40. resolve();
  41. });
  42. });
  43. },
  44. });
  45. // 动态更新 copyText
  46. if (isRef(options.copyText)) {
  47. watch(options.copyText, (copyText) => {
  48. modal.update({
  49. okButtonProps: {
  50. ...options.okButtonProps,
  51. class: COPY_CLASS,
  52. [CLIPBOARD_TEXT]: copyText,
  53. } as any,
  54. });
  55. });
  56. }
  57. return modal;
  58. }