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('已全部复制到剪切板');
};
相关推荐
黑马程序员毕设12 分钟前
基于微信小程序的二手交易平台设计与实现报告
前端·人工智能·spring boot·后端·考研
cAuth13 分钟前
实现一个图形编辑器
前端·架构·计算机图形学
Nayana39 分钟前
《Web 到 HarmonyOS》-- 嵌入 Web 与桥接基础
前端
一拳不是超人42 分钟前
之前用 AI 两小时写的塔罗网站,我真把它做上线了,然后呢?
前端·人工智能·程序员
flash俊杰2 小时前
ASR 转写与字幕时间轴:强制对齐、CPS 约束与 SRT 工程化
前端
前端炒粉2 小时前
AI工具面经
前端
唐小码2 小时前
裁员的风刮到了三线荒凉的城市
前端
晚安日记wanna2 小时前
React 为何不做双端 diff?Vue 与 React 更新逻辑的三层差异
前端·react.js·面试
flash俊杰2 小时前
AI 分段引擎与自动剪辑决策:从语义片段到时间线草稿的映射
前端·ai编程