防抖节流在网上随便一搜一大堆,但是自己拿下来用总是不能实现,可能是我自己调用的方式不对,这是我自己后来改的:
方法一:(有局限性,不能把防抖提到common.js里面)
函数部分:
//防抖函数
debounce(fn, delay) {
let _this = this
return function() {
if (_this.timer) {
clearTimeout(_this.timer)
}
_this.timer = setTimeout(fn, delay)
}
},
//测试防抖输出的
fdfunc() {
console.log("i am test the function of debounce")
},
//自己加的点击事件
testfd() {
this.debounce(this.fdfunc, 3000)()
}
timer设置为了全局变量。
调用:
<el-button type="warning" @click="testfd">测试防抖</el-button>
方法二:
debounce(fn, delay) {
let timer = null;
return function() {
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, arguments)
}, delay)
}
},
防抖函数这样写。