vue中实现输入框函数防抖debounce

防抖函数的原理:
只有在事件触发的时候才会延迟加载,如果在延迟加载之前再次触发,则会刷新延迟时间重新延迟,触发次数有且只有触发一次;

使用场景:
防抖函数一般是用于频繁触发事件,而我们只需要它触发一次的场景,比如:输入框的oninput事件、button按钮点击事件、点赞等操作场景;

实例:
例如在vue-cli脚手架中使用防抖函数来进行提升性能
vue-cli:
定义一个util.js

// 函数防抖
export function debounce(fn, wait) {
    let timeout = null;
    wait = wait || 600;
    return function () {
      let that = this;
      if(timeout !== null)   clearTimeout(timeout);  
      timeout = setTimeout(() => {
        fn.apply(that);
      }, wait);
    }    
}

(注意:我们在vue-cli中自定义方法必须要export抛出,不然组件读取不到)

使用和引用组件:

import {debounce} from "@/utils/utils"

调用方法:

methods: {
      inputNum: debounce(function(){
          console.log(1111);
      }, 1000)
  }

后记:

    // eg1 : 防抖函数
    valueChange() {
      debounce(function () {
        console.log("测试");
        return function(){}
      }, 1000);
    },
eg2:
    valueChange: debounce(function () {
       console.log("测试");
       return function(){}
    }, 1000),

注意两种函数的写法,
第一种,当valueChange执行, 触发debounce函数,并把return的函数返回到debounce上。
第二种: valueChange 是一个变量,等于debounce 返回什么值,返回的内容返回给valueChange .

vue中使用:
util.js

// 函数防抖
export default {
    debounce(fn, wait) {
        let timeout = null;
        wait = wait || 600;

        return function () {
            let that = this;
            console.log(this)
            if (timeout !== null) clearTimeout(timeout);

            timeout = setTimeout(() => {
                fn.apply(that);
            }, wait);
        }
    }
}

vue页面 使用


    // 防抖函数
    valueChange: utils.debounce(function () {
      this.inputChange();
    }, 500),
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值