以下是一个适用于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
    }
  }
}

使用方法:

  1. 在页面中引用该指令:
import debounceThrottle from '@/directives/debounce-throttle'

export default {
  directives: {
    debounceThrottle
  }
}
  1. 在需要防抖节流的元素上添加指令:
<template>
  <view v-debounce-throttle="{type: 'debounce', delay: 500, handler: handleClick}">点击我</view>
</template>

<script>
export default {
  methods: {
    handleClick() {
      console.log('点击了')
    }
  }
}
</script>

其中,type 表示防抖或节流的类型,可选值为 debouncethrottledelay 表示延迟时间,单位为毫秒,handler 表示点击事件的回调函数。

帮我封装一个适用于uniapp的防抖节流的点击事件指令

原文地址: https://www.cveoy.top/t/topic/ZCa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录