美文网首页
Vue中实现 input 表单搜索(防抖版)

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

作者: 夏海峰 | 来源:发表于2021-05-22 14:47 被阅读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)
            }
        }
    })
    

    第二种实现,使用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
            }
        }
    })
    

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

    相关文章

      网友评论

          本文标题:Vue中实现 input 表单搜索(防抖版)

          本文链接:https://www.haomeiwen.com/subject/lxnnjltx.html