vuejs-challenges
vuejs-challenges copied to clipboard
20 - 防抖点击指令
// 你的答案
<script setup lang="ts">
/**
* Implement the custom directive
* Make sure the `onClick` method only gets triggered once when clicked many times quickly
* And you also need to support the debounce delay time option. e.g `v-debounce-click:ms`
*
*/
function debounce(fn, delay) {
let timer = null
return (args) => {
if (timer) return
fn.call(this, args)
timer = setTimeout(() => {
clearTimeout(timer)
timer = null
}, delay)
};
}
const VDebounceClick = {
created(el, binding) {
el.addEventListener('click', debounce(binding.value, binding.arg))
},
};
function onClick() {
console.log('Only triggered once when clicked many times quickly');
}
</script>
<template>
<button v-debounce-click:2000="onClick">Click on it many times quickly</button>
</template>