vue2中防抖与节流的使用

本文讲述了在Vue项目中使用el-table实现全选功能时,如何通过防抖(debounce)和节流(throttle)技术来防止接口重复调用的问题,分享了防抖和节流的实现代码以及它们在输入框和文件下载场景的应用。
摘要由CSDN通过智能技术生成

项目场景:

今天在做列表的全选功能用的el-table,点击全选后面的几页也勾选上,导致了一个问题,我在selection-change回调函数中,请求的接口被反复调用,因为全选会勾选第一页每一条记录,都会触发,所以用到了防抖功能


代码片段(防抖函数)

1.这是我封装到了debounce.js文件中的防抖函数:

// 防抖函数
export function debounce(func, delay) {
    let timer = null;
    return function(...args) {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
            func.apply(this, args);
        }, delay);
    }
}

2.防抖函数项目中的运用

import {debounce} from '../../utils/debounce.js'
handleChange(){
	debounce(() => {
	  this.$store.dispatch("yangben/previewPoint", { ids: this.selectLabelAll, type: this.type });
	 }, 300) 
}

节流函数补充:

1.节流函数代码

// 节流
export const throttle=(fn, delay) => {
	// 时间戳
	var timeTwo = 0 //new Date();
	// 定时器
	var timeThree = null;
	return function() {
		let context = this;
		let args = arguments;
		var now = new Date()

		// !!!!时间戳实现【new Date()虽然获取结果不是时间戳但是计算结果会自动转化为时间戳】
		// if(now-timeTwo>=delay){
		//     fn.apply(context,args);
		//     timeTwo=new Date();
		// }

		// !!!!定时器实现
		// if (!timeThree) {
		//     timeThree = setTimeout(function () {
		//         fn.apply(context, args);
		//         timeThree=null;
		//     }, delay)
		// }

		// 结合 ps:最后一次触发在固定频率内会在延迟后触发
		var wait = delay - (now - timeTwo)
		clearTimeout(timeThree)
		if (wait <= 0) {
			fn.apply(context, args);
			timeTwo = new Date();
		} else {
			timeThree = setTimeout(function() {
				fn.apply(context, args);
			}, delay)
		}
	}
}

2.节流函数代码调用

//节流
		throttling: throttle(function (...args) {
			this.throttlingBtn(...args)
		}, 1000),

总结

防抖:
1.函数执行之后,在规定时间内如果再次触发,会清空clearTimer(),重新开始计时。前面的触发都会取消,最后一次执行规定的时间 之后才会触发。如果连续快速触发,只执行最后一次

2.应用场景:输入框输入

节流:
1.在规定时间内,只触发一次,个人理解就是有个时间段,在这个时间段执行一次

2.应用场景:文件下载(避免多次点击,下载很多个)

大家可以参考另一位博主文章: vue2项目中按钮实现防抖、节流功能,包含封装代码以及使用

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值