vue-复制剪贴板

一、 下载安装Vue 3 Composition API的工具库

npm i @vueuse/core

二、引入

import { useClipboard } from '@vueuse/core';

三、自定义hook组件

javascript 复制代码
import { useClipboard } from '@vueuse/core';

const { copy, isSupported } = useClipboard();

export function useClipboards() {
  const copyFn = isSupported ? copy : execCopyCommand;
  return {
    copyFn,
  };
}
//  如果不支持系统复制
export function execCopyCommand(text: string) {
  try {
    const textArea = document.createElement('textarea');
    textArea.value = text;
    // 使text area不在viewport,同时设置不可见
    textArea.style.position = 'absolute';
    textArea.style.left = '-100px';
    textArea.style.top = '-100px';
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    return new Promise(() => {
      // 执行复制命令并移除文本框
      document.execCommand('copy');
      textArea.remove();
    });
  } catch (e) {
    console.error('Failed to copy-e:', e);
  }
}

四、 页面中引用并实现复制

**引入hooks方法

javascript 复制代码
import { useClipboards } from '@/hooks/useClipboards';
const { copyFn } = useClipboards();

**事件定义

html 复制代码
<div style="margin-top: 20px" @dblclick="handleClick">
        <codemirror
          ref="codemirorRef"
          @ready="handleReady"
        />
      </div>

**双击事件

javascript 复制代码
const codemirorRef = ref();

const handleReady = (payload: { view: EditorView; state: EditorState; container: HTMLDivElement }) => {
  codemirorRef.value = payload.view;
};

const handleClick = () => {
    copyFn(codemirorRef.value.modelValue);
    mes.success('已全部复制到剪切板');
};
相关推荐
恋猫de小郭25 分钟前
Flutter Zero 是什么?它的出现有什么意义?为什么你需要了解下?
android·前端·flutter
崔庆才丨静觅7 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60618 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了8 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅8 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅8 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅9 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment9 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅9 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊9 小时前
jwt介绍
前端