防抖函数的使用场景: 频繁触发、输入框搜索
<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>
节流函数的使用场景:频繁触发、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触发了:' + 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)
}
}
}
},
created(){
this.fnScroll = this.fnThrottle(this.fnHandleScroll, 1000) //刚创建时执行
},
} </script>
使用时可以放到公共函数里面,然后调用使用。如在utils/index.js文件里面写
// 防抖处理-立即执行
export function posDebounce(fn, t) {
let delay = t || 500
let flag = true
let timer
return function () {
let args = arguments
if(flag) {
fn.apply(this, args)
flag = false
}
clearTimeout(timer)
timer = setTimeout(() => {
flag = true
}, delay)
}
}
然后在vue页面调用
import { _Debounce } from '@/utils';
goShopDevBind:_Debounce(function(item) {
console.log(this)
console.log(item)
}, 3000),