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