webfansplz / vuejs-challenges

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

20 - 节流点击指令 #2674

Open NoSocialStudio opened 5 months ago

NoSocialStudio commented 5 months ago
// 你的答案
<script setup lang='ts'>
function debounce(fn, delay) {
  let timer = null
  return function(...args) {
    if(timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(()=> {
      fn.apply(this, args)
      timer = null
    }, delay)
  }
}

const vDebounceClick = {
  mounted(el, {value, arg}) {
    el.addEventListener('click', debounce(value, arg))
  }
}

function onClick() {
  console.log("Only triggered once when clicked many times quickly")
}

</script>

<template>
  <button v-debounce-click:1000="onClick">
    Click on it many times quickly
  </button>
</template>