首页 > 其他 > 详细

vue实现简单防抖(watch input)

时间:2019-06-07 10:40:56      阅读:324      评论:0      收藏:0      [点我收藏+]
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秒才执行一次事件

技术分享图片

vue实现简单防抖(watch input)

原文:https://www.cnblogs.com/King-Jin/p/10987500.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!