vue 使用閉包實現防抖


參考地址:https://blog.csdn.net/qq_36262295/article/details/109510532

    https://blog.csdn.net/weixin_39939012/article/details/101211869

    https://blog.csdn.net/qq_35585701/article/details/81392174?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.control&dist_request_id=1328626.22722.16154465859786847&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.control

防抖:頻繁觸發事件后,合並事件,間隔時間內只執行一次(空閑控制)

節流:頻繁觸發事件后,控制觸發的頻率,間隔時間內再執行(縮短執行頻率,頻率控制)

開發中的常用場景:
頁面的scroll事件、onresize事件
input框等的輸入框的輸入事件、鍵盤鍵入事件
拖拽事件用到的mousemove等

 

util.js

//防抖
const debounce = function (fn, wait) {
  let timeout = null;
  return function (...args) {
    timeout && clearTimeout(timeout);
    timeout = setTimeout(() => {
      fn.apply(this, args);
    }, wait);
  };
};
export default {
debounce 
};
 

使用

http.js

import util from "./util.js";

  return new Promise((resolve, reject) => {
    if (debounce) {
      //防抖
 let fn = util.debounce(() => { let req; if (/^p/.test(method)) { req = axios[method](url, data, option); } else { option.params = data; req = axios[method](url, option); } req .then((res) => { resolve(res.data); }) .catch((err) => { reject(err.data); }); }, 500)();
   //解除引用,釋放內存 fn = null
; } else { let req; if (/^p/.test(method)) { req = axios[method](url, data, option); } else { option.params = data; req = axios[method](url, option); } req .then((res) => { resolve(res.data); }) .catch((err) => { reject(err.data); }); } });

 


免責聲明!

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



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