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('已全部复制到剪切板');
};
相关推荐
追光少年33221 小时前
Learning Vue 读书笔记 Chapter 4
前端·javascript·vue.js
软件2051 小时前
【Vite + Vue + Ts 项目三个 tsconfig 文件】
前端·javascript·vue.js
老大白菜1 小时前
在 Ubuntu 中使用 FastAPI 创建一个简单的 Web 应用程序
前端·ubuntu·fastapi
渔阳节度使1 小时前
React
前端·react.js·前端框架
LCG元3 小时前
Vue.js组件开发-如何实现异步组件
前端·javascript·vue.js
Lorcian3 小时前
web前端12--表单和表格
前端·css·笔记·html5·visual studio code
问道飞鱼3 小时前
【前端知识】常用CSS样式举例
前端·css
wl85113 小时前
vue入门到实战 三
前端·javascript·vue.js
ljz20164 小时前
本地搭建deepseek-r1
前端·javascript·vue.js
爱是小小的癌4 小时前
Java-数据结构-优先级队列(堆)
java·前端·数据结构