vue中使用闭包(例如防抖和节流)失效问题(直接调用)

文章讨论了在Vue应用中防抖和节流函数失效的问题,原因是直接在函数体内调用导致每次点击事件产生新的执行栈。解决方法是将防抖或节流函数外层绑定到事件处理函数。此外,文章提供了防抖和节流的函数实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 出现问题

防抖/节流使用无效,(例如防抖,按钮点击多次依旧执行多次)
----> 查看是闭包无效,定义的局部变量依旧为初值
----> 没有相应清除定时器

  <el-button @click="btn1">按 钮1</el-button>
  <el-button @click="debounce(btn2)">按 钮2</el-button>
</template>

<script setup lang="ts">
// 以下方法调用不生效
const btn1 = () => {
  debounce(() => {
    console.log('点击了')
  }, 1000)()
}

const btn2 = () => {
  console.log('点击了');
}

</script>
2. 问题原因

直接调用了防抖函数

原因:这个和vue的事件绑定原理有关。如果直接在函数体内部使用的话,结果就是,一个匿名的立即执行函数来进行执行。由于每次触发点击事件都会返回一个新的匿名函数, 就会生成一个新的函数执行期上下文(称之为执行栈),所以就会防抖/节流就会失效

3. 解决办法
<template>
  <el-button @click="btn">按 钮1</el-button>
</template>

<script setup lang="ts">
const btn = debounce(function() {
  console.log('点击了');
},500)
</script>
4. 防抖节流函数
type DebouncedFn<T extends (...args: any[]) => any> = (this: ThisParameterType<T>, ...args: Parameters<T>) => void;

type ThrottledFn<T extends (...args: any[]) => any> = (this: ThisParameterType<T>, ...args: Parameters<T>) => void;

function debounce<T extends (...args: any[]) => any>(fn: T, delay: number, immediate = false): DebouncedFn<T> {
  let timer: number | null = null;
  return function(this: ThisParameterType<T>, ...args: Parameters<T>) {
    // if (timer !== null) clearTimeout(timer);
    timer && clearTimeout(timer)
    if (immediate) {
      const callNow = !timer;
      timer = setTimeout(() => {
        timer = null;
      }, delay);
      callNow && fn.apply(this, args);
    } else {
      timer = setTimeout(() => {
        fn.apply(this, args);
      }, delay);
    }
  };
}

function throttle<T extends (...args: any[]) => any>(fn: T, delay: number, immediate = false): ThrottledFn<T> {
  let lastCall = 0;
  return function(this: ThisParameterType<T>, ...args: Parameters<T>) {
    const now = new Date().getTime();
    // immediate 不为 true 时, 不立即执行
    lastCall === 0 && !immediate && (lastCall = now)
    const diff = now - lastCall;
    if (diff >= delay) {
      lastCall = now;
      fn.apply(this, args);
    }
  };
}

export {
  debounce,
  throttle
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凡小多

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值