
/**
 *节流：规定时间内，只触发一次。比如我们设定500ms，在这个时间内，无论点击按钮多少次，它都只会触发一次。
 * 使用：
 * <el-button v-throttle:click.delay[2000]="testThrottle">按钮节流</el-button>
 * el-button v-throttle:click.delay[2000]="()=>testThrottle('throttle')">按钮节流传参</el-button>
 * 
 */
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) {
        binding.value()
        throttled = true
        setTimeout(() => {
          throttled = false
        }, delay)
      }
    }
    el.addEventListener(binding.arg, el.throttleEvent)
  },
  beforeUnmount(el: ThrottleEl, binding: any) {
    el.removeEventListener(binding.arg, el.throttleEvent)
  },
}

export default throttleDirective

