最近写了一个复制所绑定元素文本的vue自定义指令,给大家分享一下。
javascript">import { ElMessage } from 'element-plus'
// data-* 属性名
const dataCopyBtnTextAttribute = 'data-copy-btn-text'
// 复制按钮的class,结合项目实际进行设置
const copyBtnClass = 'icon-copy'
// 复制文本的方法
const copyText = data => {
const input = document.createElement('input')
input.setAttribute('readonly', 'readonly')
input.setAttribute('value', data)
input.style.position = 'absolute'
input.style.left = '-100px'
input.style.top = '-100px'
input.style.opacity = '0'
document.body.appendChild(input)
input.select()
document.execCommand('copy')
setTimeout(() => {
document.body.removeChild(input)
})
}
// 设置 data-* 属性
function setSign(el) {
el.setAttribute(dataCopyBtnTextAttribute, el.innerText)
}
// 移除 data-* 属性
function removeSign(el) {
el.removeAttribute(dataCopyBtnTextAttribute)
}
// 获取 data-* 属性
function getSign(el){
return el.getAttribute(dataCopyBtnTextAttribute)
}
// 生成复制按钮
function getCopyBtn(el){
const iDom = document.createElement('i')
iDom.className = `iconfont ${copyBtnClass}`
Object.assign(iDom.style,{
color:'blue',
cursor:'pointer',
marginLeft:'4px'
})
// 添加点击事件
iDom.addEventListener('click',() => {
copyText(el.innerText)
ElMessage({
message: '复制成功',
type: 'success',
duration:1000
})
})
return iDom
}
// 添加复制按钮
function addCopyBtn(el){
// 当节点内容发生变化时,移除复制按钮,当复制的文本有值时,重新添加复制按钮
if(getSign(el) !== el.innerText){
removeCopyBtn(el)
if(!!el.innerText){
el.appendChild(getCopyBtn(el))
setSign(el)
}
}
}
// 移除复制按钮
function removeCopyBtn(el){
removeSign(el)
var copyBtns = el.querySelectorAll(`.${copyBtnClass}`);
copyBtns.forEach((element) => {
el.removeChild(element)
element = null
})
}
export default {
mounted(el, binding) {
addCopyBtn(el)
},
updated(el, binding) {
addCopyBtn(el)
},
beforeUnmount(el, binding){
removeCopyBtn(el)
}
}