Vue-element-admin 学习之路

Vue element 关于下拉框输入模糊查询

2019-12-16  本文已影响0人  璃小灯吖

最近做的页面跟UI沟通过以后希望在下拉框上做个能输入模糊查询提醒的功能。自己也参考了很多的资料最后做个总结,实现如下:

方法一:

1、效果图


2、实现代码

这里是应用了<el-autocomplete>这一组件完成这个功能
HTML部分

 <el-autocomplete
        v-model="listQuery.deptName" //数据绑定用于整个的搜索功能
        :fetch-suggestions="querySearchGroup"
        placeholder="请选择"
        clearable //由于输入了内容后只会显示匹配的那一个信息想修改的话记得加这个可清空输入框内容的功能
        class="filter-item"
        style="width: 168px;margin-top:0px"
        @select="selectGroup"
        @focus="groupListMe"
  />

JS部分
定义用于存储数据的两个数组

 data() {
    return {
       groupArr: [],
       groupList: [],
  }
},

设置一个深度监听listQuery.deptName

watch: {
    'listQuery.deptName': {
      deep: true,
      handler: function(newVal, oldVal) {
        this.groupArr = []// 这是定义好的用于存放下拉提醒框中数据的数组
        var len = this.groupList.length// groupList
        var arr = []
        for (var i = 0; i < len; i++) { // 根据输入框中的值进行模糊匹配
          if (this.groupList[i].name.indexOf(this.listQuery.deptName) >= 0) {
            arr.push({
              value: this.groupList[i].name,
              id: this.groupList[i].code
            })
          }
        }
        this.groupArr = arr
      }
    }
  },

在方法中获取

methods: {
    groupListMe() { 
      getDictInfo().then(res => { // getDictInfo()这里是调用后台接口
        if (res.data) {
          this.groupList = []
          this.groupArr = []
          this.groupList = res.data.list
          for (const item of this.groupList) {
            this.groupArr.push({
              value: item.name, //这里一定是value: '值'
              id: item.code
            })
          }
        }
      })
        .catch(err => {
          console.log(err)
        })
    },
    querySearchGroup(queryString, cb) {
      var groupArr = this.groupArr
      cb(groupArr)
    },
    selectGroup(val) {
      this.groupId = val.code
    },
}

方法二:

效果图

为el-select添加filterable属性即可启用搜索功能。默认情况下,Select 会找出所有label属性包含输入值的选项。

 <el-select v-model="listQuery.deptCode" clearable filterable placeholder="请选择" style="top: -6px;">
        <el-option v-for="o in DeptOptions" 
          :key="o.code" 
          :label="o.name" 
          :value="o.name" />
      </el-select>

DeptOptions的内容是从接口中获取的。getDictInfo为调用接口的方法,关于详细请见关于Get类型接口以及关于Post类型接口

getOptionsData() {
      getDictInfo().then(res => {
        this.DeptOptions = res.data.list
        console.log('treeList', this.DeptOptions)
      })
    },

3、总结

基本的实现就是如上步骤啦!如有错误请多指教
关于官方文档中el-autocomplete的用法
关于官方文档中el-select的用法

其他关于接口的问题可以参考我的其他文章噢 ~
谢谢浏览!点个赞再走吧~

上一篇下一篇

猜你喜欢

热点阅读