Vue中实现 input 表单搜索(防抖版)
2021-05-22 本文已影响0人
夏海峰
第一种实现,给v-model
添加.lazy
修饰符,当声明式变量同步更新到响应式系统中时才调接口。参考代码如下:
<div id='app'>
<input v-model.lazy="text" />
</div>
var app = new Vue({
el: '#app',
data: {
text: ''
},
watch: {
text: function() {
console.log('失焦时调接口', this.text)
}
}
})
第二种实现,使用watch
的handle
和deep
选项,配合setTimeout()
定时器实现。参考代码如下:
<div id='app'>
<input v-model="text" />
</div>
var app = new Vue({
el: '#app',
data: {
text: '',
timer: null
},
watch: {
text: {
handler: function (val, oldVal) {
if(this.timer) clearTimeout(this.timer)
this.timer = setTimeout(()=>{
console.log('输入停止后500毫秒,开始调接口', this.text)
}, 2000)
},
deep: true
}
}
})
本篇结束,感谢点赞!!!