Skip to content

20 - 节流点击指令 #2257

Open
Open
@mu-muw

Description

@mu-muw
// 你的答案
<template>
  <button v-debounce-click="onClick">
    Click on it many times quickly
  </button>
 </template> 
 <script setup>
 // 定义 VDebounceClick 组件
 const VDebounceClick = {
  // 当组件创建时,执行以下操作
  created(el, binding) { 
    // 从 binding 中获取回调函数
    const { value: callback } = binding 
    // 为 button 添加 click 事件监听器
    el.addEventListener('click', deduce(callback))
  }
 }
 
 // 定义 deduce 函数
 function deduce(fn) {
  let timer = 0
  
  // 返回一个新的函数,用于处理 click 事件
  return function () {
    // 如果 timer 已被设置,清除之前的定时器
    if (timer) {
      clearTimeout(timer)
    }
    
    // 设置新的定时器,延迟执行 fn 函数
    timer = setTimeout(fn, 1000)
  }
 }
 
 // 定义 onClick 函数
 function onClick() {
  console.log("Only triggered once when clicked many times quickly")
 }
 </script>

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions