一、 下载安装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('已全部复制到剪切板');
};