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('已全部复制到剪切板');
};
相关推荐
weixin_5841214316 分钟前
vue内i18n国际化移动端引入及使用
前端·javascript·vue.js
Delroy27 分钟前
一个不懂MCP的开发使用vibe coding开发一个MCP
前端·后端·vibecoding
imkaifan30 分钟前
bind函数--修改this指向,返回一个函数
开发语言·前端·javascript·bind函数
xkxnq34 分钟前
第一阶段:Vue 基础入门(第 7 天)
前端·javascript·vue.js
光头闪亮亮35 分钟前
企业协同办公系统(OA)-【图标选择器】模块开发详解
前端·javascript·vue.js
pas13637 分钟前
22-mini-vue props
前端·javascript·vue.js
pas13638 分钟前
23-mini-vue 实现 emit 功能
前端·javascript·vue.js
百度地图汽车版41 分钟前
【智图译站】基于 LightGBM 与 GNSS 多特征驱动的 NLOS 误差可靠识别方法
前端
黛色正浓43 分钟前
leetCode-热题100-子串合集(JavaScript)
javascript·算法·leetcode
有意义1 小时前
用心写好一个登录页:代码、体验与细节的平衡
前端·react.js·交互设计