当前位置: 首页 > article >正文

vue-复制剪贴板

 

一、 下载安装Vue 3 Composition API的工具库

npm i @vueuse/core

 二、引入

import { useClipboard } from '@vueuse/core';

三、自定义hook组件

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方法

import { useClipboards } from '@/hooks/useClipboards';
const { copyFn } = useClipboards();

**事件定义 

<div style="margin-top: 20px" @dblclick="handleClick">
        <codemirror
          ref="codemirorRef"
          @ready="handleReady"
        />
      </div>

  **双击事件

const codemirorRef = ref();

const handleReady = (payload: { view: EditorView; state: EditorState; container: HTMLDivElement }) => {
  codemirorRef.value = payload.view;
};

const handleClick = () => {
    copyFn(codemirorRef.value.modelValue);
    mes.success('已全部复制到剪切板');
};

 


http://www.kler.cn/a/458427.html

相关文章:

  • pytorch整体环境打包安装到另一台电脑上
  • 高级技巧-使用Mysql 实现根据条件过滤整个分组数据
  • 正则化强度的倒数C——让模型学习更准确
  • Bash 脚本教程
  • 【Python】什么是元组(Tuple)?
  • TCP/IP原理
  • OpenCV-Python实战(4)——图像处理基础知识
  • 数据资产运营平台如何搭建?数据要素资产运营平台解决方案 解读
  • C++软件设计模式之代理(Proxy)模式
  • pikachu靶场搭建详细步骤
  • 爬虫入门一 基础知识 以及request
  • 【HF设计模式】04-工厂模式
  • 【论文笔记】Top-nσ: Not All Logits Are You Need
  • 游戏引擎学习第65天
  • “校园疫情防控的技术支持”:疫情管控系统的实现与评估
  • WPF系列四:图形控件Rectangle
  • 【代码分析】Unet-Pytorch
  • 【每日学点鸿蒙知识】hvigor升级、Dialog动画、LocalStorage无效、页面与子组件的生命周期、cookie设置
  • GNN图神经网络模型详解与代码复现
  • 正点原子串口例程解读