【Vue】vue使用节流与防抖注意点

防抖+节流 代码

  • 代码是木得问题滴

scr/utils/utils.js

// 防抖函数| f 要执行的函数 | deley 延时(毫秒),默认100 | firstRun 第一次是否执行 true就是执行,默认false, // // // // // // // // // // // // // 
function debounce(f, deley = 100, firstRun = false) {
    
    
    let time666
    // 第一次是否执行
    if (firstRun === true) f();

    return (_, ...args) => {
    
    
        clearTimeout(time666)
        time666 = setTimeout(__ => f.apply(_, args), deley)
    }
};

// 节流 f-函数 deley-延时
function throttle(f, deley = 500) {
    
    
    let time = null; 

    return (_, ...args) => {
    
    
        if (time !== null) return

        time = setTimeout(() => {
    
    
            f.apply(_, args)
            time = null
        }, deley);
    }
}
 
export {
    
    
    debounce, 
    throttle
}

需求+调用节流

需求

  1. 频繁点击按钮时,1200毫秒执行一次

错误调用

<template>
    <button @click="florCard.florClk1">调用1</button>
 	<button @click="throttle(lorCard.florClk2,1200)">调用2</button> 
	<button @click="throttle(lorCard.florClk3,1200)">调用3</button> 
</template>

<script setup> 
import {
      
       throttle } from '@/utils/utils'

const florCard = {
      
        
	//错误 1
     florClk1() {
      
      
        throttle(() => console.log(1), 1200)
   	 },
   	 
     //错误 2
    florClk2: function() {
      
      
     	 console.log(1);
    },
	
	// 错误 3
	  florClk3() {
      
      
          console.log(1);
     },
}
</script>

正确调用

必须定义一个变量接收防抖/节流返回的函数,如下fn

src/views/homeView.vue

<template>
    <button @click="b(1, 2, 3)">按钮1111</button> 
</template>

<script setup>
/** 
 * 定义一个变量存储防抖函数的返回值
 * 注:防抖函数返回的是一个函数,所以,fn存储的是个函数
 */
let fn = null 
const a = _ => console.log(_) 
const b = (...args) => {
      
      
 /**
  * 注:想要达到防抖与节流,最终调用的是防抖火或节流函数返回的函数
  * 若第一次调用b函数,且fn为null,则先调用防抖函数
  * 并使用fn变量存储防抖函数返回的函数 
  * 也就是说真正调用的是fn函数,而非debounce
  */
  if (!fn) {
      
      
    fn = debounce(a)
  }
  fn(args)
}

const debounce = (fn, deley = 400) => {
      
      
  let time = null
  return (...args) => {
      
      
    clearTimeout(time)
    time = setTimeout(_=> fn.apply(null, args), deley)
  }
}
</script>

注意点

防抖+节流注意点
vue事件中使用防抖/节流时,需调用防抖/节流返回的函数 。并非直接调用debounce、throttle 函数
节流+防抖原理是返回一个函数,并调用返回的这个函数,达到防抖+节流效果
  • 上面错误的调用方法,
    1. 因为调用一个普通函数,再调用防抖/节流,此时防抖/节流返回一个函数,但未调用防抖/节流返回的函数,没有达到防抖/节流效果
    2. 在防抖、节流函数后面加个小括号,是调用到防抖、节流了。但,每次点击按钮时都会不停触发防抖、节流,最终也没有达到防抖、节流效果。

End


2023/3/12 辑


2023/3/15 一改


2023/4/21 19:55 2改

猜你喜欢

转载自blog.csdn.net/qq_43614372/article/details/129475011