程序员の奇妙冒险

返回
vue JavaScript Vue
2025-08-23 16:35 阅读:90 评论:0

vue使用原生JS实现复制文本到剪贴板

实现逻辑 使用

实现逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
export function copyToClip(text: string) {
return new Promise((resolve, reject) => {
try {
const input: HTMLTextAreaElement = document.createElement('textarea')
input.setAttribute('readonly', 'readonly')
input.value = text
document.body.appendChild(input)
input.select()
if (document.execCommand('copy'))
document.execCommand('copy')
document.body.removeChild(input)
resolve(text)
}
catch (error) {
reject(error)
}
})
}

使用

1
2
3
4
5
6
# 导入
import { copyToClip } from '@/utils/copy'
# 执行复制
copyToClip(item.content).then(() => {
ElMessage.success('复制成功');
})
评论 (0)
暂无评论 来抢沙发吧~