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