防抖(debounce)
触发同一事件太快,以致于发送了多次请求,所以需要防抖 减少一段时间内事件发送的次数 减轻服务器压力 一段时间内用户无操作则发送请求 这段时间内又被触发,则重新计时。
实现原理:
设置一个定时器,通过闭包,抓住定时器变量,控制定时器的添加和清除实现防抖
在vue中 时间函数的名字在data里定义好 然后把时间函数赋给他
data () {
return {
// 定时器的名---防抖
timer: null,
}
}
methods: {
// 搜索输入框发生改变时
letter (keyword) {
// 清空计时器---防抖
clearTimeout(this.timer)
// 如果建议搜索有数据
if (this.lists.keyword.trim().length > 0) {
// 设置定时器---防抖
this.timer = setTimeout(async () => {
// 打开弹窗
this.box = true
// 把输入框里的值拿过去发请求
const res = await list({ keyword })
// 存到建议搜索的数据项里
this.suggest = res.data.items
}, 500)
} else if (this.lists.keyword.trim().length === 0) {
this.box = false
}
},
}
这里设置0.5秒内无操作执行