vue实现简单防抖(watch input)

watch监控input值,如果用户快速输入值,就会持续触发watch 事件导致掉帧,用户体验受到影响,甚至加大服务器的压力
通过防抖来优化性能

<input type="text" v-model="searchStr">


const app = new Vue({
el:"#app",
data:{
searchStr:"",
fun:null
},
watch:{
searchStr: function (str) {
if (typeof str ==='string'){
if (str.trim().length!==0){
this.debounce(this.changeStr,1000);
}else {}
}
}
},
methods:{
debounce:function(fn,wait){
if (this.fun!==null){
clearTimeout(this.fun)
}
this.fun = setTimeout(fn,wait)
},
changeStr:function(data){
console.log(data)
},
}

效果:当我持续快速向input输入时,只有停顿1秒才执行一次事件

猜你喜欢

转载自www.cnblogs.com/King-Jin/p/10987500.html
今日推荐