vue3 节流函数和防抖函数封装

1.节流函数

// utils.js  
  
//节流函数
utils.throttle = (fn, delay) => {
    
    
  let timer = null;
  return function (...args) {
    
    
    if (!timer) {
    
    
      timer = setTimeout(() => (timer = null), delay);
      return fn.apply(this, args);
    }
  };
};

这个节流函数接受两个参数:要封装的函数 fn 和延迟时间 delay。函数返回一个新的函数,这个新函数在被调用时会检查是否已经存在定时器,如果不存在,就设置一个新的定时器,并调用原始函数。如果已经存在定时器,则不再调用原始函数。
2.在 Vue3 中使用节流函数:

//温度+ 
const addTemp = proxy.$U.throttle((val, index) => {
    
    
  console.log(val)
  if (val == 34) {
    
    
    return false;
  }
  state.airConList[index].acuOutTemp = Number(state.airConList[index].acuOutTemp)
  state.airConList[index].acuOutTemp += 1
}, 1000)

3.防抖函数

import {
    
     ref, watchEffect, watch } from 'vue';  
  
function debounce(fn, delay) {
    
      
  let timeoutId;  
  return function(...args) {
    
      
    if (timeoutId) clearTimeout(timeoutId);  
    timeoutId = setTimeout(() => fn.apply(this, args), delay);  
  };  
}  
  
export default {
    
      
  setup() {
    
      
    const inputValue = ref('');  
    const handleInput = debounce((value) => {
    
      
      console.log(value); // 处理输入值的逻辑  
    }, 500);  
  
    watchEffect(() => {
    
      
      handleInput(inputValue.value);  
    });  
  
    return {
    
     inputValue };  
  }  
};

在上面的例子中,我们定义了一个 debounce 函数,这个函数接受一个函数和一个延迟时间作为参数,返回一个新的函数,这个新函数在被调用时会清除之前的定时器,并在延迟时间后执行原始函数。在 setup 函数中,我们创建了一个 inputValue 引用,并定义了一个 handleInput 函数,这个函数被 debounce 包装了一下,用来处理输入值的逻辑。然后我们使用 watchEffect 来监听 inputValue 的变化,并在变化时调用 handleInput 函数。由于 handleInput 函数被 debounce 包装了,所以它只会在输入停止 500 毫秒后被调用一次。

除了使用 watchEffect,也可以使用 watch 来监听某个值的变化。需要注意的是,在 Vue3 中,需要使用 ref 来创建一个响应式对象,这样才能在值变化时触发相应的操作。

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44705979/article/details/132872857