帮我封装一个适用于uniapp的防抖节流的点击事件指令
以下是一个适用于uniapp的防抖节流的点击事件指令的封装代码:
/**
* 防抖节流指令
* 使用方法:v-debounce-throttle="{type: 'debounce/throttle', delay: 500}"
*/
export default {
name: 'debounce-throttle',
directive: {
bind(el, binding) {
const { type, delay } = binding.value || {}
let timer = null
let lastTime = null
const handleClick = () => {
if (type === 'debounce') {
clearTimeout(timer)
timer = setTimeout(() => {
binding && binding.value && binding.value.handler(el)
}, delay)
} else if (type === 'throttle') {
const nowTime = new Date().getTime()
if (lastTime == null || nowTime - lastTime > delay) {
lastTime = nowTime
binding && binding.value && binding.value.handler(el)
}
}
}
el._handleClick = handleClick
el.addEventListener('click', handleClick)
},
unbind(el) {
el.removeEventListener('click', el._handleClick)
delete el._handleClick
}
}
}
使用方法:
- 在页面中引用该指令:
import debounceThrottle from '@/directives/debounce-throttle'
export default {
directives: {
debounceThrottle
}
}
- 在需要防抖节流的元素上添加指令:
<template>
<view v-debounce-throttle="{type: 'debounce', delay: 500, handler: handleClick}">点击我</view>
</template>
<script>
export default {
methods: {
handleClick() {
console.log('点击了')
}
}
}
</script>
其中,type 表示防抖或节流的类型,可选值为 debounce 和 throttle,delay 表示延迟时间,单位为毫秒,handler 表示点击事件的回调函数。
原文地址: https://www.cveoy.top/t/topic/ZCa 著作权归作者所有。请勿转载和采集!