webfansplz / vuejs-challenges

Collection of Vue.js challenges
https://vuejs-challenges.netlify.app/
MIT License
2.7k stars 188 forks source link

20 - 节流点击指令 (能过单元测试) #2676

Open c11ee opened 4 months ago

c11ee commented 4 months ago
<script setup lang="ts">
import { type Directive } from 'vue'

/**
 * 实现以下自定义指令
 * 确保在一定时间内当快速点击按钮多次时只触发一次点击事件
 * 你需要支持防抖延迟时间选项, 用法如 `v-debounce-click:ms`
 *
 */

let si: NodeJS.Timeout | undefined
const VDebounceClick: Directive<HTMLButtonElement> = {
  created(el, { value, arg }) {
    el.addEventListener('click', () => {
      const timeout = Number(arg)

      if (!si) {
        value()
        si = setTimeout(() => {
          si = undefined
        }, timeout)
      }
    })
  }
}

function onClick() {
  console.log('Only triggered once when clicked many times quickly')
}
</script>
<template>
  <button v-debounce-click:200="onClick">Click on it many times quickly</button>
</template>