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

 

转载于:https://www.cnblogs.com/King-Jin/p/10987500.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue2中的Input和节流可以通过自定义指令来实现。所谓和节流,是为了避免用户频繁操作输入框或者触发事件而导致过多的数据请求或者回调函数调用,从而提高页面性能和用户体验。 :在输入框或者事件触发后,等待一段时间(例如300ms),如果这段时间内没有再次输入或者触发事件,则执行回调函数;如果再次输入或者触发事件,则重新计时。 节流:在输入框或者事件触发后,等待一段时间(例如300ms),只执行一次回调函数,不管这段时间内有没有再次输入或者触发事件。 下面是Vue2中实现和节流的自定义指令代码: ``` // 指令 Vue.directive('debounce', { inserted: function (el, binding) { let timer = null; el.addEventListener('input', () => { if (timer) { clearTimeout(timer); } timer = setTimeout(() => { binding.value(); }, binding.arg || 300); }); } }); // 节流指令 Vue.directive('throttle', { inserted: function (el, binding) { let timer = null; let flag = true; el.addEventListener('input', () => { if (flag) { flag = false; timer = setTimeout(() => { flag = true; binding.value(); }, binding.arg || 300); } }); } }); ``` 使用时,可以在模板中添加指令并传入对应的回调函数和时间间隔参数: ``` <template> <input v-debounce="handleInput" :arg="500" /> <input v-throttle="handleInput" :arg="500" /> </template> <script> export default { methods: { handleInput() { // 回调函数 } } }; </script> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值