vue防抖节流
<template>
<div>
<div class="scroll" ref="previewText" @click="fnScroll">{{count}}</div>
</div>
</template>
<script>
export default{
name:'globalHospot',
data(){
return{
count:0,
fnScroll:() =>{}
}
},
methods: {
fnHandleScroll (e) {
console.log(e);
console.log('scroll触发了:' + this.count++, new Date())
},
fnThrottle(fn, delay, atleast){ //节流函数
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)
}
}
}
},
mounted() {
this.fnScroll = this.fnThrottle(this.fnHandleScroll, 1000) //刚创建时执行
},
created(){
this.fnScroll = this.fnThrottle(this.fnHandleScroll, 1000) //刚创建时执行
},
}
</script>
<style lang="less">
.scroll{
width: 300px;
border: 1px solid red;
height: 500px;
font-size: 60px;
}
</style>