1.在 data 中定义防抖的延时器 timerId 如下
data() {
return {
// 延时器的 timerId
timer: null,
// 搜索关键词
kw: ''
}
}
2.修改 input 事件处理函数如下:
input(e) {
// 清除 timer 对应的延时器
clearTimeout(this.timer)
// 重新启动一个延时器,并把 timerId 赋值给 this.timer
this.timer = setTimeout(() => {
// 如果 500 毫秒内,没有触发新的输入事件,则为搜索关键词赋值
this.kw = e.value
console.log(this.kw)
}, 500)
}
本文介绍了如何在Vue和uni-app中实现搜索框的防抖(debounce)处理,通过在data中定义延时器timerId,并改造input事件处理函数,有效地减少了频繁触发请求的次数,提高用户体验。
583

被折叠的 条评论
为什么被折叠?



