Vue中实现 input 表单搜索(防抖版)

第一种实现,给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)
        }
    }
})

第二种实现,使用watchhandledeep选项,配合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
        }
    }
})


本篇结束,感谢点赞!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章