在vue2项目中手写防抖,节流函数

153 阅读1分钟

在vue2项目中手写防抖,节流函数。

场景

image.png

监听input框的input事件,发请求。

      <input type="text" @input="throtteInput" v-model="keyword" placeholder="搜索" />
      <button>取消</button>
    </view>

对应的代码如下

const debounce = function (fn, t = 500) {
    let timerId = null
    return function(...arg) {
        clearTimeout(timerId)
        timerId = setTimeout(()=> {
            fn.apply(this,arg)
        }, t)
    }
}

const throtte = function (fn, t = 50) {
    let timerId = null
    return function(...arg) {
        if(timerId) return ;
        timerId = setTimeout(()=> {
            fn.apply(this,arg)
            timerId = null
        }, t)
    }
}
export default {
    data() {
        return {
            keyword: '', // 关键字
        }
    },
    created() {
        this.debounceInput = debounce(this.hInput , 300)
        this.throtteInput = throtte(this.hInput , 300)
    },
    methods:{
        async hInput(e) {
            console.log(this.keyword, e)
            const {data} = await this.$request({url: 'goods/qsearch', data:{query: this.keyword}})
            console.log(data)
        }
    }
}

这里里面的代码有几点注意事项:

  1. input框上的input事件回调函数是直接在created钩子中定义的,并不是在methods中
  2. 注意this的绑定问题。
const debounce = function (fn, t = 500) {
    let timerId = null
    return function(...arg) {
        clearTimeout(timerId)
        timerId = setTimeout(()=> {
            // 箭头函数内部的this值就是 function(...arg){} 中this的值
            fn.apply(this,arg)
        }, t)
    }
}

@input="throtteInput":当input事件被触发时,会执行throtteInput,同时绑定当前组件到执行上下文,所以fn.apply(this,arg)中的this就是当前组件,而fn就是this.hInput 3. 注意arg的问题。要能正确地接收到调用函数时传入的参数。