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('已全部复制到剪切板');
};
相关推荐
名字还没想好☜3 小时前
React 用 useEffect 做轮询实战:setInterval 拿到旧 state 的闭包陷阱与正确清理
前端·javascript·react.js·react·useeffect
hiahiahia1233 小时前
AI Web 项目的文件到底应该怎么放?
前端·人工智能
愚公搬代码4 小时前
【愚公系列】《Web应用安全》003-测试环境的搭建
前端·安全
_codemonster4 小时前
主流前端技术分层选型
前端
SendTomo5 小时前
P2P文件传输工具对比:SendTomo vs send.wang
javascript·网络协议·webrtc·html5·p2p
犹豫的果冻布丁6 小时前
从零给 DeepSeek Harness 写一个壁纸皮肤插件(已开源)
前端·后端
漏刻有时6 小时前
数据可视化Three.js 3D 地图实战:单文件原生实现省域区县拉伸建模
前端
会说话的番茄6 小时前
AI 满嘴跑火车怎么办?给它配个"小抄"
前端·aigc
计算机魔术师6 小时前
AI 权力集中辩论实录:从「token 工厂」到「唯一幸存者」
前端
eric-sjq6 小时前
WanlyFrontend 中文声明式前端语言完全指南:让 0.6B 模型写出漂亮网页
前端