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


原文:https://blog.csdn.net/weixin_42735794/article/details/91388550

 

函数防抖

定义:多次触发事件后,事件处理函数只执行一次,并且是在触发操作结束时执行。

在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)
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM