CopyButton 复制按钮

将一段文本写入剪贴板的按钮,并给出复制成功的反馈。

pnpm add @hina-ui/vue
<script setup lang="ts">
  import { Code, CopyButton, Inline } from '@hina-ui/vue'
</script>

<template>
  <Inline align="center">
    <Code>pnpm add @hina-ui/vue</Code>
    <CopyButton text="pnpm add @hina-ui/vue" />
  </Inline>
</template>
vue

用法

import { CopyButton } from '@hina-ui/vue'
ts

text 是必填属性,它的内容会写入剪贴板。复制成功后,图标由复制切换为选中标记,按钮的名称同时变为“已复制”,两秒后自动恢复。

<script setup lang="ts">
  import { CopyButton } from '@hina-ui/vue'
</script>

<template>
  <CopyButton text="Hina UI" />
</template>
vue

示例

尺寸

默认为 sm。复制按钮通常紧跟在一段文本或者一行命令之后,sm 与相邻文字的高度最为接近。

<script setup lang="ts">
  import { CopyButton, Inline } from '@hina-ui/vue'
</script>

<template>
  <Inline align="center">
    <CopyButton size="sm" text="小号" />
    <CopyButton size="md" text="中号" />
    <CopyButton size="lg" text="大号" />
  </Inline>
</template>
vue

名称与提示

默认名称为“复制”。如果页面上有多个复制按钮,应当通过 label 说明各自复制的内容,并且打开 tooltip,便于在点击之前区分。

复制成功之后名称固定切换为“已复制”,自定义的名称在这段时间内不显示。

<script setup lang="ts">
  import { CopyButton, Inline } from '@hina-ui/vue'
</script>

<template>
  <Inline align="center">
    <CopyButton text="ssh://git@example.com/hina.git" label="复制仓库地址" tooltip />
    <CopyButton text="hina-2f9c41" label="复制订单编号" tooltip />
  </Inline>
</template>
vue

复位时长

timeout 决定成功状态持续的时间,默认为 2000 毫秒。如果按钮位于较长的表单中或者页面的边缘,可以适当延长,便于使用者注意到反馈。

<script setup lang="ts">
  import { CopyButton, Inline } from '@hina-ui/vue'
</script>

<template>
  <Inline align="center">
    <CopyButton text="默认两秒" />
    <CopyButton text="五秒后复位" :timeout="5000" />
  </Inline>
</template>
vue

复制事件

复制成功时组件会触发 copied 事件,参数为写入剪贴板的文本。失败时不触发。

已复制 0 次

<script setup lang="ts">
  import { ref } from 'vue'
  import { CopyButton, Inline, Text } from '@hina-ui/vue'

  const count = ref(0)
</script>

<template>
  <Inline align="center">
    <CopyButton text="hina@example.com" @copied="count++" />
    <Text tone="muted">已复制 {{ count }} 次</Text>
  </Inline>
</template>
vue

剪贴板的限制

浏览器只在安全上下文中提供剪贴板接口,页面需要通过 HTTPS 或者 localhost 访问。在 file:// 打开的页面以及部分内嵌页面中,写入会被拒绝。

写入失败时按钮不会进入成功状态,图标与名称都保持原样,也不会触发 copied 事件。

无障碍

  • 按钮的默认名称为“复制”,复制成功后变为“已复制”,屏幕阅读器会读出这一变化。
  • 按钮渲染为原生的 button,可以通过键盘聚焦,回车键与空格键都能够触发。
  • 提示默认关闭,需要时通过 tooltip 打开。

API

Props

属性
类型
默认值
说明
text
string
—
必填。写入剪贴板的文本
label
string
复制
按钮的无障碍名称
size
'xs' | 'sm' | 'md' | 'lg'
'sm'
尺寸
timeout
number
2000
成功状态持续的毫秒数
tooltip
boolean
false
是否显示提示
disabled
boolean
false
是否不可用
class
string
—
追加至按钮的类名

Events

事件
参数
说明
copied
text: string
写入剪贴板成功时触发