VUE3实现防抖节流

export function simpleDebounce(fn, delay = 100) {
  let timer: any | null = null;
  return function () {
    let args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      // @ts-ignore
      fn.apply(this, args);
    }, delay);
  };
}

函数防抖方法---(抄袭别人的,我这就当个笔记)

使用方法

 const draggable1Sort = simpleDebounce(updataRosterpersonnel, 5000);

一定要定义一下,再使用这个防抖的方法

function updataRosterpersonnel (){
      console.log("防抖成功")
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 2中实现防抖节流的方法是通过自定义指令或者在方法中使用`setTimeout`来实现的。下面分别介绍两种方式的实现: 1. 使用自定义指令实现防抖节流: ```javascript // 使用自定义指令 v-debounce Vue.directive('debounce', { inserted: function (el, binding) { let timer = null; el.addEventListener('input', function () { if (timer) { clearTimeout(timer); } timer = setTimeout(() => { binding.value(); }, 500); // 设置延迟时间,单位为毫秒 }); } }); // 使用自定义指令 v-throttle Vue.directive('throttle', { inserted: function (el, binding) { let timer = null; el.addEventListener('input', function () { if (!timer) { timer = setTimeout(() => { binding.value(); timer = null; }, 500); // 设置间隔时间,单位为毫秒 } }); } }); ``` 在模板中使用自定义指令: ```html <input v-debounce="handleInput" /> <input v-throttle="handleInput" /> ``` 其中`handleInput`为需要防抖或者节流的方法。 2. 在方法中使用`setTimeout`实现防抖节流: ```javascript export default { data() { return { timer: null } }, methods: { debounce(method, delay) { clearTimeout(this.timer); this.timer = setTimeout(() => { method(); }, delay); }, throttle(method, interval) { if (!this.timer) { method(); this.timer = setTimeout(() => { this.timer = null; }, interval); } }, handleInput() { // 防抖示例 this.debounce(() => { // 处理输入事件 }, 500); // 节流示例 this.throttle(() => { // 处理输入事件 }, 500); } } } ``` 在模板中绑定方法: ```html <input @input="handleInput" /> ``` 以上两种方式都可以实现防抖节流效果,根据具体的需求选择合适的方式即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值