Vue的click事件防抖和节流处理

1,948 阅读1分钟

函数防抖

  • 在vue中对click添加防抖处理

const on = Vue.prototype.$on
// 防抖处理
Vue.prototype.$on = function (event, func) {
    let timer
    let newFunc = func
    if (event === 'click') {
        newFunc = function () {
            clearTimeout(timer)
            timer = setTimeout(function () {
                func.apply(this, arguments)
            }, 500)
        }
    }
    on.call(this, event, newFunc)
}

函数节流

  • 在vue中对click添加节流处理

const on = Vue.prototype.$on
 
// 节流
Vue.prototype.$on = function (event, func) {
    let previous = 0
    let newFunc = func
    if (event === 'click') {
        newFunc = function () {
            const now = new Date().getTime()
            if (previous + 1000 <= now) {
                func.apply(this, arguments)
                previous = now
            }
        }
    }
    on.call(this, event, newFunc)
}