21、防抖, 一段时间内只执行最后一次请求;节流, 一段时间内只执行第一次请求

192 阅读1分钟
import { debounce, throttle } from 'lodash'
Vue.prototype.$debounce = debounce // 防抖
Vue.prototype.$throttle = throttle // 节流
mounted () {
    this.resizeFn = this.$debounce(() => {
      this.moveToTarget(this.activeMenu)
    }, 500)
    window.addEventListener('resize', this.resizeFn)
    
    //this.initTableHeight()
    //this.resizeFn = this.$debounce(this.initTableHeight, 500)
  },

1、封装

//防抖, 一段时间内只执行最后一次请求
      debounce(fn, delay = 1000) {
        let that = this;
        this.timer && clearTimeout(this.timer);
        this.timer = setTimeout(function () {
          fn.apply(that);
        }, delay)
      }

2、调用

<input v-model="userName" label="手机号" placeholder="请输入" type="number" @input="validPsw"/>

//防抖
validPsw() {
        this.debounce( function () {
          this.placeholder = '请输入';
          api.pswIsChanged(this.userName).then(res => {
            if (!res.data) {
              this.placeholder = '用户初始密码为人员编号';
            }
          });
        }, 1000);
      },
      
      
//节流
imgLoadError(item) {
   const token = item.path.match(/\?token=([^&]*)$/)
       if (token) {
          this.throttle(this.resetToken, 10000)()
   }
 },

3、总结

//节流, 一段时间内只执行第一次请求
    throttle(fn, delay = 1000) {
        let that = this
        const begin = this.begin || 0
        this.begin = Date.now()
        return function (...args) {
            let current = Date.now()
            if (current - begin > delay) {
                fn.apply(that, args)
            }
        }
    },
    //防抖, 一段时间内只执行最后一次请求
    debounce(fn, delay = 1000) {
        let that = this
        let timer = this.timer
        return function (...args) {
            clearTimeout(timer)
            that.timer = setTimeout(function () {
                fn.apply(that, args);
            }, delay)
        }
    },