防抖函數(shù)的使用場景: 頻繁觸發(fā)厅翔、輸入框搜索
<template>
<div>
<input type='text' v-model='value' @keydown = "hangleChange">
</div>
</template>
<script>
function debounce(func, wait=1000){ //可以放入項目中的公共方法中進行調用(鵝只是省事)
let timeout;
return function(event){
clearTimeout(timeout)
timeout = setTimeout(()=>{
func.call(this, event)
},wait)
}
}
export default{
name:'',
data(){
return{
value:''
}
},
methods:{
hangleChange:debounce(function(e){
console.log(this.value)
})
}
}
</script>
節(jié)流函數(shù)的使用場景:頻繁觸發(fā)晋涣、onrize伙菊,onscroll滾動條
<template>
<div class="scroll" ref="previewText" @scroll.passive="fnScroll">
</template>
<script>
export default{
name:'globalHospot',
data(){
return{
count:0,
fnScroll:() =>{}
}
},
methods: {
fnHandleScroll (e) {
console.log('scroll觸發(fā)了:' + this.count++, new Date())
},
fnThrottle(fn, delay, atleast){ //節(jié)流函數(shù)
let timer = null;
let previous = null;
return function(){
let now = +new Date()
if(!previous) previous = now;
if(atleast && now - previous > atleast){
fn();
previous = now;
clearTimeout(timer)
}else{
clearTimeout(timer)
timer = setTimeout(()=>{
fn();
previous = null
},delay)
}
}
}
},
created(){
this.fnScroll = this.fnThrottle(this.fnHandleScroll, 1000) //剛創(chuàng)建時執(zhí)行
},
}
</script>