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

节流:

含义:顾名思义,节流就是在一定的时间内同一事件无论触发多少次,对应的事件处理函数都只是每间隔规定事件执行一次;

使用场景:比较适用于搜索框的模糊查询、滚动条变化等;

防抖:

含义:防抖就是在一定的时间内同一事件无论触发多少次,对应的事件处理函数都只执行最后一次;

使用场景:比较适用于通过正则校验输入框输入信息、浏览器窗口大小变化等;

 

在vue中的大致使用:

1、在untils内新建debounceAndThrottle.js文件,添加对应的节流及防抖函数,文件内容如下:

fn对应的时间处理函数,delay间隔时间,immediate第一次是否立即执行
// 防抖
const debounce = function (fn, delay,immediate) {
  let timer = null;
  return function () {
    let that = this;
    let arg = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    if (immediate) {
      let bool = !timer;
      timer = setTimeout(() => {
        timer = null;
      },delay);
      if (bool) {
        fn.apply(that, arg);
      }
    } else {
      timer = setTimeout(() => {
        timer = null;
        fn.apply(that, arg);
      },delay)
    }
  }
}

// 节流
const throttle=function(fn,delay,immediate){
  let timer=null;
  return function(){
    let that=this;
    let arg=arguments;
    if(immediate){
      if(!timer){
        timer=setTimeout(()=>{
          timer=null;
        },delay)
        fn.apply(that,arg);
      }
    }else{
      if(!timer){
        timer=setTimeout(()=>{
          timer=null;
          fn.apply(that,arg);
        },delay)
      }
    }
  }
}

export { debounce,throttle };

2、在vue组件内使用:

<template>
  <div class="practice">
    <input type="text" v-model="inputValue" @input="input(1,2)">
  </div>
</template>

<script>
import {debounce,throttle} from "../utils/debounceAndThrottle.js";
export default {
  name: 'practice',
  data() {
    return {
      inputValue:null,
      timer:null,
    }
  },
  created() {
  },
  methods: {
    // 防抖
    // a,b为外部传递的参数
    input:debounce(function(a,b){
      console.log(a,b)
    },1000,true),

    // 节流
    input:throttle(function(a,b){
      console.log(a,b)
    },1000,true),
  },
}
</script>

<style lang="scss" scoped>
</style>

 

posted @ 2023-02-03 14:51  Alex-Song  阅读(1662)  评论(0编辑  收藏  举报