vue全局防抖和节流

函数防抖

防抖分为两种: 

 一种是立即执行:频繁触发事件,第一次触发时执行函数,后面触发不会执行,停止触发,间隔一定时间之后再触发事件,函数才会再次执行

另一种是后执行:频繁触发事件,事件只会在触发事件之后间隔定义的时间,函数才会被执行,而且只会执行最后一次触发的事件。  

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

// 防抖处理-立即执行
const on = vue.prototype.$on
Vue.prototype.$on = function (event, func) {
let timer;
let flag = true;
let newFunc = func
if (event == 'click') {
newFunc = function () {
if(flag) {
func.apply(this, arguments)
flag = false
}
clearTimeout(timer)
timer = setTimeout(function () {
flag = true
}, 500)
}
}
on.call(this, event, newFunc)
}



// 防抖处理 -- 最后执行
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)
}

vi设计http://www.maiqicn.com 办公资源网站大全https://www.wode007.com

函数节流

定义:

事件触发后,会先执行一次事件函数,执行之后如果在规定时间间隔内再触发事件,将不出触发函数,超过规定的事件间隔后会再次触发一次,如此往复

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

使用方式:选择一种,将代码复制粘贴在main.js即可。

  

原文地址:https://www.cnblogs.com/xiaonian8/p/13705330.html