指令定义
export const vCopy = {
mounted(el,{value}) {
el.$value = value
el.handler = ()=>{
if(!el.$value){
alert("无复制内容")
return
}
const textArea = document.createElement('textarea')
//将textarea设置为readonly 防止ios下自动唤起键盘,同时将textarea移出可视区域
textArea.readOnly = 'readonly'
textArea.style.position = 'absolute'
textArea.style.left = '-9999px'
textArea.value = el.$value
//插入到body中
document.body.appendChild(textArea)
//选中文本
textArea.select()
// 另一种写法textArea.setSelectionRange(0,textArea.value.length)
const result = document.execCommand('copy')
if(result){
alert('复制成功')
}
document.body.removeChild(textArea)
}
el.addEventListener('click',el.handler)
},
//当组件更新的时候触发
updated(el,{binding}) {
el.$value = value
},
unmounted(el){
el.removeEventListener('click',el.handler)
}
}
指令注册
app.directive("copy",vCopy)
使用方式
<script setup>
import { ref } from 'vue';
let text = ref('你好我叫阿东')
</script>
<template>
<button v-copy="text">一键复制</button>
<span>{{text}}</span>
</template>
<style scoped></style>