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金額)變化它一定會請求后台
}

...

原文章來源


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM