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