directive.ts 917 Bytes
import {App, DirectiveBinding} from 'vue'

export default (app: App<Element>) => {
  app.directive('debounceClick', {
    mounted(el: HTMLElement, binding: DirectiveBinding) {
      // console.log(binding)
      let timer: NodeJS.Timeout | null = null
      el.addEventListener('click', () => {
        let firstClick: Boolean = !timer;
        if (firstClick) {
          // console.log('第一次:'+ firstClick)
          binding.value()
        }
        if (timer) {
          clearTimeout(timer)
          // console.log('不执行timer,click状态:' + firstClick)
        }
        timer = setTimeout(() => {
          timer = null
          // console.log('1秒后清除timer')
          if (binding.arg && binding.arg === 'two') {
            // 最后执行一次
            // console.log('清除timer后再执行一次')
            binding.value()
          }
        }, 1000);
      })
    }
  })
}