vue防抖节流

js文件

// 防抖
export const fangDouFun = (fn, delay, immediate) => {
	var time = null,
		result; //被缓存
	return function() {
		let context = this;//记录一下this指向
		let args = arguments;
		//清除定时任务
		if (time) clearTimeout(time);
		// 第一次点击是否立即执行
		if (immediate) {
			result = fn.apply(context, args)
			immediate = false;

			// 超过delay时间immediate重置为true 
			time = setTimeout(function() {
				time = null;
				immediate = true;
			}, delay)
		} else {
			time = setTimeout(function() {
				time = null;
				result = fn.apply(context, args)
				immediate = true;
			}, delay)
		}
		return result
	}
}
// 节流
export const jieliuFun=(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)
		}
	}
}

在需要使用的vue页面引入

import { fangDouFun, jieliuFun } from '@/utils/debounceThrottle'

template中

    <van-search
            v-model="searchVal"
            show-action
            :placeholder="placeholderVal"
            @search="onSearch"
            @cancel="onCancel"
            @input="onInput"    
        />

data中

searchVal:"",
   watch:{
        // searchVal(news){
        //     this.onInput(news)
        // }
    },

watch中的可以不用
举例防抖

    onInput:fangDouFun(function(val){
            this.blockShow = 2;
            console.log(val);
            // 发送请求,获取实时搜索的文本提示的数据列表
            GetSearchTipsListData({keyword:val}).then(res=>{
                if(res.errno == 0){
                    this.searchTipsListData = res.data
                }
            })
        },3000),

感谢优秀博主
coderDeng

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值