网络编程
位置:首页>> 网络编程>> JavaScript>> 在vue中使用防抖和节流,防止重复点击或重复上拉加载实例

在vue中使用防抖和节流,防止重复点击或重复上拉加载实例

作者:FiveBigNiu  发布时间:2024-05-22 10:28:01 

标签:vue,防抖,节流,重复点击,上拉加载

废话不多说,直接上代码吧!


/**
* 函数防抖 (只执行最后一次点击)
* @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);
   }
 }
};

用法


...
methods:{
getAliyunData:Throttle(function(){
...
},1000),
}
...

来源:https://blog.csdn.net/qq_34764577/article/details/82952368

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com