函数防抖
import Vue from 'vue'
Vue.directive('noMoreClick', {
inserted (el, binding) {
el.addEventListener('click', e => {
el.classList.add('is-disabled')
el.disabled = true
setTimeout(() => {
el.disabled = false
el.classList.remove('is-disabled')
}, 2000)
})
}
})
弹窗拖拽
Vue.directive('dialogDrag', {
bind (el, binding, vnode, oldVnode) {
const dialogHeaderEl = el.querySelector('.el-dialog__header')
const dragDom = el.querySelector('.el-dialog')
dialogHeaderEl.style.cursor = 'move'
const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null)
dialogHeaderEl.onmousedown = (e) => {
const disX = e.clientX - dialogHeaderEl.offsetLeft
const disY = e.clientY - dialogHeaderEl.offsetTop
let styL, styT
if (sty.left.includes('%')) {
styL = +document.body.clientWidth * (+sty.left.replace(/\%/g, '') / 100)
styT = +document.body.clientHeight * (+sty.top.replace(/\%/g, '') / 100)
} else {
styL = +sty.left.replace(/\px/g, '')
styT = +sty.top.replace(/\px/g, '')
};
document.onmousemove = function (e) {
const l = e.clientX - disX
const t = e.clientY - disY
dragDom.style.left = `${l + styL}px`
dragDom.style.top = `${t + styT}px`
}
document.onmouseup = function (e) {
document.onmousemove = null
document.onmouseup = null
}
}
}
})
溢出省略指令
Vue.directive("textOverflow", (el) => {
Vue.nextTick(() => {
let text = el.innerHTML;
if (!text || !text.length) return;
for (let i = 0; i <= text.length; i++) {
el.innerHTML = text.substring(0, i);
if (el.offsetHeight < el.scrollHeight) {
el.style.overflow = "hidden";
el.innerHTML = text.substring(0, i - 3) + "...";
break;
}
}
});
});
文本拷贝指令
<template> <button v-copy="copyText">复制</button> </template>
Vue.directive("copy",
{
bind (el, { value }) {
el.$value = value
el.handler = () => {
if (!el.$value) {
console.log('无复制内容')
return
}
const textarea = document.createElement('textarea')
textarea.readOnly = 'readonly'
textarea.style.position = 'absolute'
textarea.style.left = '-9999px'
textarea.value = el.$value
document.body.appendChild(textarea)
textarea.select()
const result = document.execCommand('Copy')
if (result) {
console.log('复制成功')
}
document.body.removeChild(textarea)
}
el.addEventListener('click', el.handler)
},
componentUpdated (el, { value }) {
el.$value = value
},
unbind (el) {
el.removeEventListener('click', el.handler)
}
});
图片懒加载
const vLazy: Directive<HTMLImageElement, string> = async (el, binding) => {
const defaultUrl = await import('../../assets/logo-mini.svg');
el.src = defaultUrl.default;
const observer = new IntersectionObserver((enr: any) => {
if (enr[0].intersectionRatio > 0) {
setTimeout(() => {
el.src = binding.value;
}, 1000);
observer.unobserve(el);
}
});
observer.observe(el);
};