节流指令

import { ObjectDirective } from 'vue'

interface ThrottleEl extends HTMLElement {
  throttleEvent: () => void
}

// 节流指令封装
const throttleDirective: ObjectDirective = {
  beforeMount(el: ThrottleEl, binding: any) {
    let throttled = false
    let delay: number = 1000
    const keys = Object.keys(binding.modifiers)
    if (keys) {
      const key: string | undefined = keys.find((key) => key.includes('delay'))?.toString()
      const value = (key ?? '').match(/(?<=\[).*?(?=\])/)
      if (value) delay = parseInt(value[0])
    }
    el.throttleEvent = () => {
      if (!throttled) {
        throttled = true
        setTimeout(() => {
          binding.value()
          throttled = false
        }, delay)
      }
    }
    el.addEventListener(binding.arg, el.throttleEvent)
  },
  beforeUnmount(el: ThrottleEl, binding: any) {
    el.removeEventListener(binding.arg, el.throttleEvent)
  },
}

export default throttleDirective

指令注册


import throttle from '上面代码文件'
app.directive('throttle',throttle)

具体使用

<el-button v-throttle:click.delay[500]="clickEvent">切换语言</el-button>

CSDN关联地址

posted on 2023-12-21 15:20  独醉_一杯小酒  阅读(118)  评论(0编辑  收藏  举报