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秒才执行一次事件




					


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM