100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Vue实现 input 输入框下拉搜索提示功能

Vue实现 input 输入框下拉搜索提示功能

时间:2020-05-03 17:10:16

相关推荐

Vue实现 input 输入框下拉搜索提示功能

效果图如下:

需求:input 中分别有focus 和 blur 方法,当 input 聚焦时,我们的下拉选项显示出来;当 input 失去焦点时,我们的下拉选项隐藏。如果用户向 input 框中输入文字后,下拉选项中的文字显示与之匹配的信息。

html 中分别添加 focus 方法和 blur 方法。

<input type="text" placeholder="请输入客户信息" class="inputInfo" v-model="searchcursom" v-on:focus="focusCustomer()" v-on:blur="blurCustomer()" />

在两个方法中,分别切换下拉框列表的显示和隐藏。当下拉框显示时,将调用getSelectData 方法,获取到需要显示到下拉框中的数据。

focusCustomer(){if(document.querySelector('input') == document.activeElement){this.getSelectData(this.searchcursom.trim());}this.showCustomer = true},blurCustomer() {this.showCustomer = false},

当我们不断输入数据时,下拉框中数据需要不断地与输入框中的信息相匹配,此时我们需要使用 watch 监听,即监听用户向 input 框中的输入信息。当监听到数据变化时,重新触发focusCustomer 方法。

watch: {'searchcursom': {handler: function() {this.focusCustomer()}}},

显示下拉框数据:

<ul class="sel-ul customer-ht" v-show="showCustomer"><div class="text-center loading" v-show="showloading"><inline-loading></inline-loading><span style="vertical-align:middle;display:inline-block;font-size:14px;">&nbsp;&nbsp;加载中</span></div><div v-show="!showloading"><div v-show="customerList.length"><li v-for="(item, index) in customerList" :value="item" :key="index" @click="chooseCustomer(item)">{{item}}</li></div><div class="text-center" v-show="!customerList.length">暂无数据返回</div></div> </ul>

按照上述内容,我们可以在浏览器中测试 自定义input 输入下拉搜索功能是没有问题的,但是使用手机测试时,li 标签的 点击事件无法触发,导致 input 框中的内容不能立即换成点击 li 标签上的内容。

当用户点击 input 框时或着聚焦 input 框时,我们显示 li 标签,点击 input 以外的地方,我们则采用全局监听,隐藏 li 标签。代码如下:

mounted() {let that = thisdocument.addEventListener('click',function(e){if(e.target.className != 'inputInfo'){that.$nextTick(() => {that.showCustomer = false;})}})}

这里我们使用全局监听点击 input 框以外的界面,那么取消 blur 方法中对 li 标签的隐藏,即问题解决。

优化:

这里主要是优化一下对于输入时不断地请求接口,我们使用防抖进行优化。当我们在停止输入的某一段时间内,才会触发接口请求。

focusCustomer(){if(document.querySelector('input') == document.activeElement){this._debounce(500)// this.getSelectData(this.searchcursom.trim());}this.showCustomer = true},//函数防抖_debounce(wait){ clearTimeout(this.timer)this.timer=setTimeout(()=>{this.getSelectData(this.searchcursom.trim());},wait)}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。