VUE中的函数的防抖和节流 以及应用场景

先看看概念

函数防抖(debounce):

在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时;典型的案例就是输入搜索:输入结束后n秒才进行搜索请求,n秒内又输入的内容,就重新计时。

应用场景:

  • search搜索联想,用户在不断输入值时,用防抖来节约请求资源。
  • window触发resize的时候,不断的调整浏览器窗口大小会不断的触发这个事件,用防抖来让其只触发一次

函数节流(throttle):

规定在一个单位时间内,只能触发一次函数,如果这个单位时间内触发多次函数,只有一次生效; 典型的案例就是鼠标不断点击触发,规定在n秒内多次点击只有一次生效。

应用场景:

  • 鼠标不断点击触发,mousedown(单位时间内只触发一次)
  • 监听滚动事件,比如是否滑到底部自动加载更多,用throttle来判断

我们将防抖和节流函数写在utils文件夹下面需要的时候引用

export function _debounce(fn, delay) {
//防抖
  var delay = delay || 200;
  var timer;
  return function () {
    var th = this;
    var args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function () {
      timer = null;
      fn.apply(th, args);
    }, delay);
  };
}
// 节流
export function _throttle(fn, interval) {
  var last;
  var timer;
  var interval = interval || 200;
  return function () {
    var th = this;
    var args = arguments;
    var now = +new Date();
    if (last && now - last < interval) {
      clearTimeout(timer);
      timer = setTimeout(function () {
        last = now;
        fn.apply(th, args);
      }, interval);
    } else {
      last = now;
      fn.apply(th, args);
    }
  }
}

引用

<template>
    <div>
        <input type="button" value="+1" @click="add">
        <br>
        <input type="button" value="-1" @click="reduce">
    </div>
</template>

<style>
    input{
        width: 200px;
        height: 20px;
    }
</style>

<script>
  import { _debounce } from '@/utils/debounce'
  import { _throttle } from '@/utils/debounce'
  import { mapState, mapActions } from 'vuex'
    export default {
      computed: {
        ...mapState({
//          kindlist: ({ kind: { kindlist } }) => kindlist, //{ kind: { kindlist } }=state.kind,kindlist
//          brandlist: (state) => state.kind.brandlist,
//          prolist: ({ kind }) => kind.prolist  //kind=state.kind
          count:(state)=>state.count.count,
        })
      },
      methods:{
        add:_debounce(function(_type, index, item){  //防抖
           this.$store.dispatch('count/add')
        },2000),
        reduce:_throttle(function(){
            this.$store.dispatch('count/reduce')
          },2000)
        },
    }
</script>
原文地址:https://www.cnblogs.com/hy96/p/12188296.html