移动端会有一个搜索框,输入的时候就会在输入框下面弹出搜索结果
image.png
这个情况就会用到防抖
dom
<template>
<input @input="changeValue"></input>
</template>
首先,创建一个防抖函数
debounce(fn,delay){
let timer = null
return function(){
let that = this
let args = arguments
if (timer){
clearTimeout(timer)
}
timer = setTimeout(()=>{
fn.apply(that,args)
},delay)
}
}
在mounted里面取出防抖函数
mounted(){
this.updateValue = this.debounce(search,500)
}
methods
// 接口请求
search(val) {
//在这里获取val去调用接口
}
// input框的change事件
changeValue(e){
this.updateValue(e.target.value)
}
总结: 防抖就是在事件(比如input输入事件)触发n秒后执行回调(搜索),如果在n秒内再次触发事件(输入事件),则回调的执行时间就会重新计算,比如时间间隔是2s,在1.5s再次触发事件,那么回调则会在3.5s后执行
网友评论