Vue中的debounce应用
背景:优化搜索框的功能,在输入过程中,可以实时动态进行搜索,但是为了提高搜索效率,频繁进行查询,需要进行防抖
解决办法:在输入过程中,在一定时间内没有输入,再进行查找,采用debounce;
因此在编程时,需要注意两点:
第一:监听输入数据的变化,触发搜索(监听一般想到的是watch)
第二:进行防抖,并不是所有的输入,都需要进行搜索,采用定时来实现
具体实践:
方法1:
监听数据变化,执行debounce,不直接使用watch:{}是因为debounce不能直接在watch中使用,应该放在created中
//监听input数据,当数据变化的时候,触发debounce
this.$watch('input',this.debounce(()=>{
this.search()//具体需要执行的函数
},3000))
具体debounce函数实现
debounce(fn, delay){
var timer = null;
return function() {
var self = this,
args = arguments;
clearTimeout(timer);
timer = setTimeout(function() {
fn.apply(self, args)
}, delay);
}
},
如果想直接使用watch()来监听,可以参考方法2
方法2:
监听到变化后,触发一个emitDebounce函数,这个函数不是debounce,而是通过这个函数再去触发debounce
watch:{
input(){
this.emitDebounce({vm:this})
}
},
给emitDebounce绑定debounce
editDebounce: debounce(({ vm, val, verifyEmail }) => {
console.log('codeing')
}, 300
debounce函数实现
const debounce = (func, wait) => {
let timeout = '';
return (v) => {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
func(v);
}, wait);
}
个人更推荐方法1 ,思路更为清晰,且this指向明确,但在第一次使用时,会直接将debounce写在watch中,然后进入无止尽的调试。。。
方法2中debounce中的this不指向vue实例,需要将this作为一个参数传参,新手容易迷糊