做项目时有一个搜索框输入搜索,因为按一下键盘就会触发一次请求接口,会造成性能的浪费,所以就想到使用防抖来解决这个问题:
防抖(当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时):
data(){
timer:nul
}
methods:{
search(){
if(this.timer)//如果timer不为null,说明连续触发了事件
clearTimeout(this.timer)//清除上一次事件触发设置的定时器
}
this.timer=setTimeout(()=>{
/*
* 请求接口方法
*/
),500}
}
}
另外还有一个滚动条触发事件:
滚动条事件在一次滚动过程中会触发很多次,但我们一般都只需要一次滚动触发一次事件即可,所以这样也会造成性能的浪费,所以我使用了节流的方法。
节流(当持续触发事件时,保证一定时间段内只调用一次事件处理函数):
data(){
timer:null
},
methods:{
handleScroll(){
const that=this
return function(){
if(!that.timer){
that.timer=setTimeout(()=>{
let top= (document.body.scrollTop || document.documentElement.scrollTop || window.pageXOffset)
if (top > 100) {
that.active = true
} else {
that.active = false
}
that.timer = null
},500)
}()
}
}