1.鼠标点击复制
let listener:EventListenerOrEventListenerObject
export const copy = {
mounted: (el: Element, binding: DirectiveBinding)=>{
listener = ()=>{
let copyText = el.textContent || ""
navigator.clipboard.writeText(copyText)
}
el.addEventListener("click", listener)
},
unmounted(el: Element) {
if(listener) {
el.removeEventListener("click", listener)
}
},
}
2. 鼠标点击后,复制指定元素内容的textContent
let listener2:EventListenerOrEventListenerObject
export const copyByButton = {
mounted(el: Element, binding: DirectiveBinding) {
listener2 = async ()=> {
let target = document.querySelector(`.${binding.value.class}`)
if(target) {
await navigator.clipboard.writeText(target.textContent || "")
}
}
el.addEventListener("click", listener2)
},
unmounted(el: Element) {
if(listener2) {
el.removeEventListener("click", listener2)
}
},
}
3. 节流
import _ from "lodash"
import { DirectiveBinding, onMounted } from "vue"
let listener: EventListenerOrEventListenerObject
function throttle(func: Function, wait: number) {
let lastTime = 0
return function() {
let now = + new Date()
if(now - lastTime > wait) {
func()
lastTime = now
}
}
}
export const debounce = {
mounted(el: Element, binding: DirectiveBinding) {
let func = binding.value
listener = throttle(func, 1000)
el.addEventListener("click", listener)
},
onMounted(el: Element) {
if(listener) {
el.removeEventListener("click", listener)
}
}
}
4.懒加载
import { DirectiveBinding } from "vue"
import vue from "@/assets/vue.svg"
export const lozyload = {
mounted(el: HTMLImageElement, binding: DirectiveBinding) {
el.src = vue
let observer = new IntersectionObserver((entries)=> {
if(entries[0].isIntersecting) {
el.src = binding.value
observer.unobserve(el)
}
})
observer.observe(el)
},
}