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

效果图如下:

Vue实现 input 输入框下拉搜索提示功能_第1张图片

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

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

在两个方法中,分别切换下拉框列表的显示和隐藏。当下拉框显示时,将调用 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()
    }
  }
},

显示下拉框数据:

     
              加载中  
     
       
         
  • {{item}}
  •    
       
    暂无数据返回
     
           

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

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

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

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

你可能感兴趣的:(vue,Vue,input输入框,下拉搜索提示功能,focus,和,blur,方法,watch,监听)