Vue中使用函数防抖和节流

函数防抖(Debounce):指触发事件后在n秒内函数只执行一次,如果在n秒内又触发了事件,则会重新计算函数执行时间。:搜素框,滚动条
函数节流(throttle):指连续触发事件但在n秒中只执行一次,避免某些事件频繁触发。:按钮点击

Vue中使用防抖和节流

第一步:定义公共防抖和节流函数

export default {

  /**
   * 函数防抖
   * 触发事件后在n秒后执行,如果n秒内又触发事件,则重新计算时间
   */
  debounce(fn, wait = 1000) {
    let timer;
    return function () {
      let context = this;
      let args = arguments;
      if (timer) clearTimeout(timer);
      timer = setTimeout(() => {
        fn.apply(context, args);
      }, wait)
    }
  },

  /**
   * 函数节流
   * 触发事件立即执行,但在n秒内连续触发则不执行
   */
  throttle(fn, wait = 1000) {
    let timer;
    return function () {
      if (timer != null) return;
      let context = this;
      let args = arguments;
      fn.apply(context, args);
      timer = setTimeout(() => {
        timer = null;
      }, wait);
    }
  },
}

注意:
防抖和节流函数中return的函数不能使用箭头函数,如果使用箭头函数则this就会指向globalFunction,就会有问题

第二步:新建Vue组件

<template>
  <div class="wrapper">
    <div @click="btnDebounce('函数','防抖')">函数防抖</div>
    <div @click="btnThrottle('函数','节流')">函数节流</div>
  </div>
</template>

第三步:引用globalFunction并在methods中使用

<script>
  import globalFunction from "../../utils/globalFunction";

  export default {
    name: "test",
    methods: {

      btnDebounce: globalFunction.debounce(function (str1, str2) {
        console.log(str1, str2);
      }, 2000),

      btnThrottle: globalFunction.throttle(function (str1, str2) {
        console.log(str1, str2);
      }, 2000),

    }
  }
</script>

说明:
globalFunction类的debounce、throttle返回的一个函数,就相当于

btnDebounce: function () {
        let context = this;
        let args = arguments;
        console.log(this);
        console.log(args);
      }

所以可以拿到当前this和arguments参数,因为argument获取的是一个类似数组的对象,所以可以通过调用函数的apply方法来传递参数

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值