Skip to content

20 - 防抖点击指令 #2040

Open
Open
@kid1110

Description

@kid1110
// 你的答案
<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:Function,delay:number){
  let timer = null
  return function(){
    if(timer){
      clearTimeout(timer)
    }
    timer = setTimeout(fn,delay)
  }
}
const VDebounceClick = {
  mounted(el,binding){
    let d = debounce(binding.value,binding.arg)
    el.addEventListener('click',d)
  }
}

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>

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions