Vue 防抖函数的实现(watcher监听某个输入框值得变化去请求后台特别好用)

申明:复制他人文章目的是为了下次自己用方便(此处因页面太多watcher监听的输入框调用后台,未防止报429,故在网上找到此文章,经本人测试,监听器方法也可用)
节流和防抖常用与监听滚动事件,移动事件,窗口改变大小事件,输入事件(例如监听一个输入框去请求后台)等高频触发事件,当事件处理函数较为复杂时,将导致无法实时响应,降低用户体验度,影响效率,出现页面卡顿,假死等现象。
debounce 周期内有新事件触发,清除旧定时器,重置新定时器;这种方法,需要高频的创建定时器。
throttling 周期内有新事件触发时,重置定时器开始时间撮,定时器执行时,判断开始时间撮,若开始时间撮被推后,重新设定延时定时器。
1.定义模块文件并导出防抖函数和节流函数//debThr.js

/**
 * 函数防抖 (只执行最后一次点击)
 * @param fn
 * @param delay
 * @returns {Function}
 * @constructor
 */
export 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
 */
export 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);
        }
    }
};

 

2.在组件中导入函数

import {
        Debounce,
        Throttle
    } from '@/common/config/debThr.js';

 

3.methods、watch中调用
...

methods:{
/*
    小提示:不要写成回调函数的形式 this指向改变了
*/
    getAliyunData:Throttle(function(){
    ...
     },1000),//1秒只执行此方法一次,比如此方法为点击事件,只要点击,他一定会执行
},
//在监听器中调用
watch: {
XZSBTCJE:Throttle(function(value){
                    debugger
                    if (value === '' || value === 0 || value === NaN) {
                        this.XZSBRate = "";
                        this.XZSBTCF = "";
                        this.XZSBSSTCF = "";
                    } else {
                        // 调后台方法
                        let list = this.multipleSelection;
                        let je = 0;
                        let bh = '';
                        for (var i of list) {
                            je += parseInt(i.ItemPrice);
                            bh = bh + i.ItemId + ",";
                        }
                        let h = this.StartDate;
                        XZSBTFJS(value, this.tfxjobj.cheldm, this.CSRate, bh, h).then(res => {
                            let xz = (res.response).split("|");
                            this.XZSBRate = (parseFloat(xz[0])).toFixed(2);
                            this.XZSBTCF = Math.round(parseFloat(xz[1])).toFixed(2);
                            this.XZSBSSTCF = Math.round((parseFloat(this.XZSBTCF) * this.ZXFL1 * (1 - (parseFloat((this.WPCYHBL1).split(
                                "%")[0])) / 100)) / 100).toFixed(2);
                            this.xzsbdisabled = false;
                            debugger
                        }).catch(err => {
                            this.$message({
                                type: "info",
                                message: "查询新增设备参数失败!"
                            });
                        })
                    }
                 },1000),//1秒只执行此方法一次,而且只要XZSBTCJE(新增设备tc金额)变化它一定会请求后台
}

...

原文章来源

posted @ 2020-09-30 16:25  我不是习小贵  阅读(1060)  评论(0编辑  收藏  举报