1.有问题的防抖版本:
<input type="text" value="" return-key-type="search" @input="replaceInput" class="fz30 inp_content" />
replaceInput(e) { // 每输入一个值 input事件都会触发,会导致timer一直都是空的,不会清空timer
let timer = null
console.log(timer);
if(timer) {
console.log('清除');
clearTimeout(timer)
}
timer = setTimeout(()=>{
console.log('执行啦');
let val = e.detail.value
console.log(val);
timer = null
},1000)
},
控制台输出:
2.解决问题的防抖版本:timer设置为全局
data() {
return {
timer: null
};
},
replaceInput(e) {
console.log(this.timer);
if(this.timer) {
console.log('清除');
clearTimeout(this.timer)
}
this.timer = setTimeout(()=>{
console.log('执行啦');
let val = e.detail.value
console.log(val);
this.timer = null
},1000)
},
控制台输出:
3.在h5中一定要使用v-model的方式
<input type="text" value="" @input="search" v-model="searchValue" return-key-type="search"
:autofocus="isFocus" class="fz30 inp_content" />
search(e) {
if (this.timer) {
clearTimeout(this.timer)
}
this.timer = setTimeout(() => {
console.log(this.searchValue);
this.timer = null
this.getSearchList(this.searchValue)
}, 1000)
},