VueUse中响应式剪切板如何实现的?
只能说是,心血来潮, 把VueUse中响应式剪切板的实现原理研究了一遍。
写这篇文章的目的当然只是记录一下下啦
源码地址: Vueuse: useClipboard
代码示例
实现逻辑
支持剪切板时使用navigator!.clipboard.writeText, 反之使用document.execCommand('copy')
1、写入
-
设备支持剪切板并启用剪切板时(即read属性值为false)
// navigator!.clipboard.writeText
await navigator!.clipboard.writeText(value)
// document.execCommand('copy')
function legacyCopy(value: string) {
// 创建一个临时的文本区域元素
const ta = document.createElement('textarea')
// 隐藏文本区域元素
ta.value = value ?? ''
ta.style.position = 'absolute'
ta.style.opacity = '0'
// 将文本区域元素添加到页面上
document.body.appendChild(ta)
// 选中文本内容
ta.select()
// 执行复制操作
document.execCommand('copy')
// 移除文本区域元素
ta.remove()
}
-
当设备不支持剪切板或者支持剪切板且不使用剪切板时(即read属性值为true)
使用useEventListener | VueUse监听
['copy', 'cut']事件来进行更新。
useEventListener(['copy', 'cut'], updateText)
2、读取
通过text进行访问
3、当执行复制操作后, 开启loading,启动定时器, 过了多少秒后(copiedDuring = 1500),loading设置为true
结尾
只能说,有点意思!!!