MPVUE 函数防抖与节流

本人小白一个,刚入职1个月,遇到搜索框实时更新会出现服务器429错误(请求过多),因此在网上找了很多方法,显然防抖节流就是我要的,奈何萌新一枚,将前人的代码改了改,终于能放进自己的mpvue,其实有很多vue防抖的博文,这里只是给纯萌新一个参考,毕竟我也是找了很久
先看一下什么是防抖和节流
函数防抖(debounce):当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。

函数节流(throttle):当持续触发事件时,保证一定时间段内只调用一次事件处理函数。

代码如下

公共.js

/**
 * 函数防抖 (只执行最后一次点击)
 * @param fn
 * @param delay
 * @returns {Function}
 * @constructor
 */
const Debounce = (fn, t) => {
    let delay = t || 500;
    let timer;
    console.log(fn)
    console.log(typeof fn)
    return function () {
        let args = arguments;
        if(timer){
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            timer = null;
            fn.apply(this, args);
        }, delay);
    }
};
/**
 * 函数节流
 * @param fn
 * @param interval
 * @returns {Function}
 * @constructor
 */
const Throttle = (fn, t) => {
    let last;
    let timer;
    let interval = t || 500;
    return function () {
        let args = arguments;
        let now = +new Date();
        if (last && now - last < interval) {
            clearTimeout(timer);
            timer = setTimeout(() => {
                last = now;
                fn.apply(this, args);
            }, interval);
        } else {
            last = now;
            fn.apply(this, args);
        }
    }
};
module.exports.Debounce = Debounce

最后一句module.exports.Debounce = Debounce是将本方法声明出去(萌新友好性,大佬勿喷)

项目.vue


<script>
//文件引入,路径自行更改即可
	import optimization from '../../static/optimization/optimization.js'
	export default {
		data() {
			inputwares:''
		},
		methods: {
		searchWares: optimization.Debounce(function() {
		console.log("正常写方法就好")
		console.log("将 searchWares(res){代码片段} 中的 代码片段 直接放进来")
		console.log(inputwares)
		},1000)
		}
	}

项目.vue中html部分

<input v-model="inputwares" @input="searchWares" placeholder="请输入商品名称"/>

searchWares为每次搜索框更新时调用方法
inputwares为输入内容复值给data内的字段

本人萌新,只是不想让大家迷路,大佬勿喷,不足之处请见谅

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

_默_

别打赏了,点点赞,点点关注就行

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

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

打赏作者

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

抵扣说明:

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

余额充值