在vue中使用防抖函数或节流函数

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 14:22   263   0

防抖和节流在这里就不多做解释了,对于防止用户多次快速点击时,或者懒加载等场景中会使用到这两种常用的限制函数。

防抖:

首先是防抖的函数:

/**
 * 防抖处理 适用于点击事件
 * @param {function}  func        回调
 * @param {number}    wait      时间窗口的间隔
 * @param {boolean}    immediate     是否立即执行
 */


export function debounce(func, wait = 500, immediate = true){
 let timer, ctx, args;
 const later = () => setTimeout(() => {
  timer = null;
  if (!immediate) {
   func.call(ctx, ...args);
   ctx = args = null;
  }
 }, wait);

 return function (){
  if (!timer) {
   timer = later();
   if (immediate) {
    func.call(this, ...arguments);
   }else{
    ctx = this;
    args = arguments;
   }
  } else {
   clearTimeout(timer);
   timer = later();
  }
 };
}

防抖函数的大概的原理就是当持续触发事件时,一定时间段内没有再触发事件

触发原函数(func)过后会有一个setTimeout时间(wait),在这个时间内再次触发原函数(func)的时候不会执行原函数,并且再次重置一次setTimeout,所以效果为连续触发后只会执行最后一次操作。

immediate 参数的作用就是是否马上执行原函数,如果参数immediate为false的话,不会马上触发原函数,而是等待wait时间后才会触发。

在vue中使用:

在vue中使用时,只需要引入之后在原函数外层包裹一下即可

// 首先引入防抖函数debounce

import {debounce} from './toolbox';

// template中click事件不变

<Button @click="createLive('creatRoom')">创建</Button>

// methods中事件的逻辑部分被包裹,type就是参数,如果没有参数就不用填

createLive: debounce(function (type) {
    console.log('这里面是函数逻辑');
}, 1000)

节流:

项目中并没有用到节流,但是大概写了一个函数供参考。

/**
 * 节流处理  适用于懒加载等场景
 * @param {function}  func      回调
 * @param {number}    wait      时间窗口的间隔
 */

export function throttle(func, wait= 1000) {
 let timer, canRun  = true;
 const later = () => setTimeout(() => {
  func.call(this, ...arguments);
  canRun = true;
 }, wait);

 return function () {
  if (!canRun) return;
  canRun = false;
  clearTimeout(timer);
  timer = later();
 };
}

节流函数的大概原理就是当持续触发事件时,保证一定时间段内只调用一次事件处理函数

在vue中使用起来与防抖是一样的。

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP