Vue 封装防抖、节流自定义指令

防抖自定义指令 v-debounce (点击事件)

1. 新建 debounce.js

import { ref, onMounted, onUnmounted } from 'vue';

export default {
  mounted(el, binding) {
    const func = binding.value;
    let timer;
    el.addEventListener('click', (e) => {
      if (timer) clearTimeout(timer);
      timer = setTimeout(() => func(e), 300); // 300ms 是延迟时间,可以根据需要调整
    });
  },
  unmounted(el) {
    el.removeEventListener('click', () => {});
  }
};

2. 安装并导入自定义指令 src/directive/index,js

import debounce from './path-to-debounce-directive';

app.directive('debounce', debounce);

3. 使用方法

<button v-debounce="handleClick">Click me (debounced)</button>


节流自定义指令 v-throttle (点击事件)

1. 新建 throttle.js

import { ref, onMounted, onUnmounted } from 'vue';

export default {
  mounted(el, binding) {
    const func = binding.value;
    let lastCall = 0;
    const delay = 300; // 300ms 是间隔时间,可以根据需要调整
    el.addEventListener('click', (e) => {
      const now = new Date().getTime();
      if (now - lastCall < delay) {
        return;
      }
      lastCall = now;
      func(e);
    });
  },
  unmounted(el) {
    el.removeEventListener('click', () => {});
  }
};



2. 安装并导入自定义指令 src/directive/index,js

import throttle from './path-to-throttle-directive';

app.directive('throttle', throttle);

3. 使用方法

<button v-throttle="handleClick">Click me (throttled)</button>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值