Skip to content

copy 复制到剪贴板指令

用于在点击等事件下,将文本复制到系统剪贴板。支持直接文本、函数动态获取、来源元素读取、成功/失败回调等。

安装与引入

按需导入(推荐)

ts
import { VCopy } from '@cuixingjian/cui-utils'

全局注册

ts
import { createApp } from 'vue'
import { VCopy } from '@cuixingjian/cui-utils'

const app = createApp(App)
app.directive('copy', VCopy)
app.mount('#app')

局部注册

vue
<script setup lang="ts">
import { VCopy as vCopy } from '@cuixingjian/cui-utils'
</script>

<template>
  <button v-copy="'复制内容'">复制</button>
</template>

效果演示

基础用法

点击按钮复制文本到剪贴板。

使用代码

直接传字符串:

vue
<template>
  <button v-copy="'Hello World'">复制 Hello World</button>
</template>

传函数(支持异步):

vue
<script setup lang="ts">
async function getText() {
  await new Promise(r => setTimeout(r, 200))
  return 'Async Text'
}
</script>

<template>
  <button v-copy="getText">复制动态文本</button>
</template>

从元素读取:

vue
<template>
  <input id="copy-input" value="输入框的值" />
  <button v-copy="{ source: '#copy-input' }">复制输入框文本</button>
</template>

API 说明

指令值类型

类型说明示例
string直接传入复制文本v-copy="'Hello'"
Function传入获取文本的函数v-copy="getText"
Object传入配置对象v-copy="{ text: 'Hello', onCopied }"

配置选项 (CopyOptions)

参数类型默认值说明
textstring直接指定复制文本
getText() => string | Promise<string>动态获取文本(支持异步)
sourceElement | string文本来源元素或选择器
attrstring'data-copy'从 source 读取的属性名
enabledbooleantrue是否启用指令
eventsstring[]['click']绑定的事件列表
preventbooleanfalse是否阻止默认行为
stopbooleanfalse是否阻止事件冒泡
capturebooleanfalse是否在捕获阶段监听
onCopied(text: string, event: Event) => void复制成功回调
onError(error: any, event: Event) => void复制失败回调

注意事项

文本获取优先级

  1. text - 直接指定的文本
  2. getText - 函数返回的文本
  3. source - 从指定元素读取
  4. 元素自身的 data-copy 属性或 textContent

复制实现

  • 优先使用 navigator.clipboard.writeText(现代浏览器)
  • 不支持时降级为 document.execCommand('copy')(旧浏览器)
  • HTTPS 环境下 Clipboard API 可用性更好

最佳实践

  • 提供成功/失败回调以改善用户体验
  • 异步获取文本时注意错误处理
  • 移动端建议添加视觉反馈

源码展示

展开查看完整源码
ts
import type { Directive } from 'vue'
import { withInstallDirective } from '../install'

export interface CopyOptions {
  text?: string
  getText?: () => string | Promise<string>
  source?: Element | string
  attr?: string
  enabled?: boolean
  events?: string[]
  prevent?: boolean
  stop?: boolean
  capture?: boolean
  onCopied?: (text: string, event: Event) => void
  onError?: (error: any, event: Event) => void
}

// 详见 packages/utils/directives/copy.ts
export const VCopy = withInstallDirective(copy, 'copy')