Skip to content

v-copy 指令

v-copy 是一个用于复制文本到剪贴板的 Vue 指令。支持简单值和对象配置两种使用方式。

基础用法

直接在元素上使用 v-copy 指令,传入要复制的内容:

loading

指令值类型

该指令支持以下两种传值方式:

简单值

直接传入要复制的内容:

vue
<button v-copy="'要复制的文本'">
复制
</button>

对象配置

传入一个配置对象,可以自定义成功/失败的回调:

vue
<button v-copy="{
  text: '要复制的文本',
  success: () => console.log('复制成功'),
  error: (err) => console.error('复制失败', err)
}"
>
  复制
</button>

配置选项

参数说明类型必填
text要复制的文本内容string | number
success复制成功的回调函数() => void
error复制失败的回调函数(err: Error) => void

使用示例

复制静态文本

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

复制动态内容

vue
<script setup lang="ts">
import { ref } from 'vue'

const dynamicText = ref('动态内容')
</script>

<template>
  <button v-copy="dynamicText">
    复制动态内容
  </button>
</template>

自定义回调

vue
<template>
  <button
    v-copy="{
      text: '自定义提示',
      success: () => {
        console.log('自定义成功提示')
      },
      error: (err) => {
        console.error('自定义错误处理', err)
      },
    }"
  >
    复制并自定义提示
  </button>
</template>

注意事项

  1. 该指令会自动为目标元素添加点击事件
  2. 复制功能依赖 Clipboard API,请注意浏览器兼容性
  3. 指令会在组件卸载时自动清理事件监听器
  4. 数字类型的值会被自动转换为字符串后复制

反馈提示

  • 复制成功:显示 "复制成功" 提示
  • 复制失败:显示 "复制失败" 提示,并在控制台输出具体错误信息

Released under the MIT License.