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('已全部复制到剪切板');
};
相关推荐
IT_陈寒19 分钟前
JavaScript的这个隐式转换特性差点让我加班到凌晨
前端·人工智能·后端
Loadings24 分钟前
AI时代下的前端安全加固实践:安全、体积与性能之间的取舍
前端
计算机魔术师1 小时前
OpenAI 首个踩红线的 AI 模型来了:能自己挖漏洞,但只给少数人用
前端
闲坐含香咀翠1 小时前
从 132MB 到 25MB:列式存储怎么把 CPU 缓存命中率提上去的
前端·数据结构·性能优化
闲坐含香咀翠1 小时前
把 AntV S2 列头计算从 O(n²) 降到 O(n):一次开源组件的性能改造
前端·性能优化
闲坐含香咀翠1 小时前
Worker 常驻 + 零拷贝:postMessage 的结构化克隆算法与 Transferable 的真实代价
前端·性能优化
JunjunZ1 小时前
Naive UI 虚拟级联选择器适配 Element Plus 风格
前端·javascript·vue.js
ynchyong2 小时前
微信小程序启动顺序遇到的一个坑
前端·微信小程序
用户233376852182 小时前
接口卡死排查实录-缺失return的UB死循环
前端·后端