主题
useClipboard
响应式 剪贴板 API。提供响应剪贴板命令(剪切、复制和粘贴)的能力,以及异步读取和写入系统剪贴板的功能。访问剪贴板内容需要通过 权限 API 授权。未经用户许可,不允许读取或修改剪贴板内容。
🌐 Reactive Clipboard API. Provides the ability to respond to clipboard commands (cut, copy, and paste) as well as to asynchronously read from and write to the system clipboard. Access to the contents of the clipboard is gated behind the Permissions API. Without user permission, reading or altering the clipboard contents is not permitted.
通过 Vue School 提供的这节免费视频课程,学习如何以响应式方式将文本保存到剪贴板!示例
用法
🌐 Usage
vue
<script setup lang="ts">
import { useClipboard } from '@vueuse/core'
const source = ref('Hello')
const { text, copy, copied, isSupported } = useClipboard({ source })
</script>
<template>
<div v-if="isSupported">
<button @click="copy(source)">
<!-- by default, `copied` will be reset in 1.5s -->
<span v-if="!copied">Copy</span>
<span v-else>Copied!</span>
</button>
<p>Current copied: <code>{{ text || 'none' }}</code></p>
</div>
<p v-else>
Your browser does not support Clipboard API
</p>
</template>选项
🌐 Options
| 选项 | 类型 | 默认值 | 描述 |
|---|---|---|---|
source | MaybeRefOrGetter<string> | — | 当调用 copy() 且未传入参数时,默认要复制的内容 |
read | boolean | false | 启用在复制/剪切事件时读取剪贴板内容 |
copiedDuring | number | 1500 | copied 在重置为 false 之前的毫秒数 |
legacy | boolean | false | 如果剪贴板 API 不可用,则回退到 document.execCommand |
返回值
🌐 Return Values
| 属性 | 类型 | 描述 |
|---|---|---|
isSupported | ComputedRef<boolean> | 是否支持剪贴板(原生或旧版) |
text | Ref<string> | 当前剪贴板内容(当 read: true 时) |
copied | Ref<boolean> | 成功复制后 true,自动重置 |
copy | (text?: string) => Promise<void> | 将文本复制到剪贴板 |
传统模式
🌐 Legacy Mode
如果剪贴板 API不可用,请设置 legacy: true 以保持复制功能。它将使用execCommand作为备用来处理复制。
🌐 Set legacy: true to keep the ability to copy if Clipboard API is not available. It will handle copy with execCommand as fallback.
ts
const { copy, isSupported } = useClipboard({ legacy: true })组件用法
🌐 Component Usage
vue
<template>
<UseClipboard v-slot="{ copy, copied }" source="copy me">
<button @click="copy()">
{{ copied ? 'Copied' : 'Copy' }}
</button>
</UseClipboard>
</template>