Skip to content

20 - 节流点击指令 #1829

Open
Open
@klbss1995

Description

@klbss1995
// 你的答案
<!--
小贴士:

🎉 恭喜你成功解决了挑战,很高兴看到你愿意分享你的答案!

由于用户数量的增加,Issue 池可能会很快被答案填满。为了保证 Issue 讨论的效率,在提交 Issue 前,请利用搜索查看是否有其他人分享过类似的档案。

你可以为其点赞,或者在 Issue 下追加你的想法和评论。如果您认为自己有不同的解法,欢迎新开 Issue 进行讨论并分享你的解题思路!

谢谢!
-->


```vue
// 你的答案
<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`
 *
*/
import {watch} from 'vue'
const VDebounceClick = {
 
	mounted:(el,binding)=>{
             let delay = binding.arg;
             el.addEventListener('click',()=>{
        if(delay != binding.arg){
        	  return;
        }
      binding.value();
	const inter = setInterval(()=>{
        if(delay==0){
          delay = binding.arg;
          clearInterval(inter);
          return;
        }
        delay--;
      },1)
    })
  },
}

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>


<!--

或者 Vue SFC Playground 在线链接 (https://sfc.vuejs.org)

-->

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions