自定义指令双击复制
1,公共方法
import { onBeforeUnmount } from 'vue'
import { message } from 'ant-design-vue'
const copy = {
mounted(el: any, binding: any) {
let timer: any
const method =
Object.keys(binding.modifiers).find(key => binding.modifiers[key]) ||
'dblclick'
const debouncedHandler = (event: any) => {
console.log(event.target)
clearTimeout(timer)
timer = setTimeout(() => {
const target = event.target
const textToCopy = target.textContent.trim()
copyToClipboard(textToCopy)
}, binding.arg || 0)
}
el.addEventListener(method, debouncedHandler)
onBeforeUnmount(() => {
el.removeEventListener(method, debouncedHandler)
})
},
}
// 定义复制到剪贴板的函数
const copyToClipboard = async (text: any) => {
try {
await navigator.clipboard.writeText(text)
message.success('复制成功')
} catch (error) {
console.error('复制失败:', error)
message.error('复制失败')
}
}
export default copy
可以挂载到全局进行使用
2,使用方式在需要的地方直接使用v-copy
<div v-copy:dblclick="handleClick" arg="300"></div>
原文地址:https://blog.csdn.net/weixin_45869811/article/details/140604470
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!