vuejs-challenges icon indicating copy to clipboard operation
vuejs-challenges copied to clipboard

20 - 节流点击指令

Open shenrui1 opened this issue 1 year ago • 0 comments

// 你的答案

<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`
 *
 */
let timeoutId = null;

const VDebounceClick = {
  mounted(el, { value, arg }) {
    el.addEventListener('click', () => {
      if (!timeoutId) {
        value();
        timeoutId = setTimeout(() => {
          clearTimeout(timeoutId);
        }, arg);
      }
    });
  },
  beforeUnmount(el, { value }) {
    clearTimeout(timeoutId);
    el.removeListener('click', value);
  },
};

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>

shenrui1 avatar Jan 19 '24 13:01 shenrui1