Appearance
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)
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| text | string | — | 直接指定复制文本 |
| getText | () => string | Promise<string> | — | 动态获取文本(支持异步) |
| source | Element | string | — | 文本来源元素或选择器 |
| attr | string | 'data-copy' | 从 source 读取的属性名 |
| enabled | boolean | true | 是否启用指令 |
| events | string[] | ['click'] | 绑定的事件列表 |
| prevent | boolean | false | 是否阻止默认行为 |
| stop | boolean | false | 是否阻止事件冒泡 |
| capture | boolean | false | 是否在捕获阶段监听 |
| onCopied | (text: string, event: Event) => void | — | 复制成功回调 |
| onError | (error: any, event: Event) => void | — | 复制失败回调 |
注意事项
文本获取优先级
text- 直接指定的文本getText- 函数返回的文本source- 从指定元素读取- 元素自身的
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')