Skip to content

Throttle Directive

源码
ts
app
  .mount('#app')
  .directive('throttle', {
    mounted(el, binding) {
      const [callback, time = 300, arg = [], immediate = false]: [
        Function,
        number,
        any[],
        boolean,
      ] = binding.value

      let bol = true
      // 只执行一次
      let only = true
      el.addEventListener('click', () => {
        // 是否立即执行
        if (immediate && only) {
          only = false
          callback(...arg)
        }

        if (bol) {
          bol = false
          setTimeout(() => {
            bol = true
            callback(...arg)
          }, time)
        }
      })
    },
  })

Released under the MIT License.