element plus 中Select 选择器提供利用筛选功能快速查找选项功能

还提供了输入关键字以从远程服务器中查找数据

 基于以上进行封装

创建组件

<!-- 
 
  1.placeholder:占位符
  示例:
    :placeholder="'Please_enter_customer_ID'"
  2.SelectData:下拉框数据
    此处有有一个重要逻辑,原本这个数据是子组件接收源数据在进行处理,但是这样子无法自适应各种数据的字段,所以使用父组件去进行处理,处理完成在传给子组件
  示例:
    :SelectData="CustomerIDData"
    this.CustomerIDData = CustomerID.data.map((item) => {
      return {value : item.CustomerID.toString() , label : item.CustomerID.toString()}
    })
-->
<template>
  <div class="RangeSearch">
    <el-select
      v-model="employeesData.transshipmentdepot"
      multiple
      filterable
      remote
      reserve-keyword
      :placeholder="$t(placeholder)"
      :remote-method="transshipmentdepotremoteMethod"
      :focus="transshipmentdepotremoteMethod"
      :loading="loading">
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value">
      </el-option>
    </el-select>
  </div>
</template>
 
<script>
export default {
  data(){
    return{
      options: [],
      value: [],
      list: [],
      loading: false,
      employeesData:{
        transshipmentdepot:'',
      },
      data:[]
    }
  },
  props:{
    placeholder:{
      default(){
        return [];
      }
    },
    SelectData:{
      default(){
        return [];
      }
    }
  },
  methods:{
    transshipmentdepotremoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.options = this.list.filter(item => {
            return item.label.toLowerCase()
              .indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.options = []
      }
    }
  },
  watch:{
    SelectData:function(newVal){
      this.options = newVal
      this.list = newVal
    }
  },
}
</script>
 
<style>
 
</style>
  • multiple:是否多选
  • filterable:是否可搜索
  • remote:是否为远程搜索
  • reserve-keyword:多选且可搜索时,是否在选中一个选项后保留当前的搜索关键词
  • loading:是否正在从远程获取数据
  • placeholder:占位符(我这里是因为需要做语言切换不需要的话直接传需要显示的字段即可)
  • focus:当input框得到焦点时触发,达到我想要的一开始点击就会出现下拉列表
  • remote-method:远程搜索方法:
  1. 定义方法并且接收query
  2. 判断query是否为空,如果为空则跳出判断,并将options赋值为空
  3. 将loading设置为true,开始加载
  4. 这里做了一个定时器,200毫秒后才会执行定时器中的内容
  5. 进入定时器将loading设置为false,结束加载
  6. 将options赋值为通过筛选的数据,该方法最终会返回true和false,为true则渲染,达到模糊搜索的目的

使用组件 


<template>
  <div>
		<RangeSearch
		  :placeholder="'Please_enter_customer_ID'"
		  :SelectData="CustomerIDData"
		></RangeSearch>
  </div>
</template>
 
<script>
import RangeSearch from '@/components/RangeSearch.vue'
export default {
  components:{
    RangeSearch,
  },
  data(){
    return{
      CustomerIDData:[],  //客户ID数据
    }
  },
  mounted(){
    this.CustomerIDData = CustomerID.data.map((item) => {
      return {value : item.CustomerID.toString() , label : item.CustomerID.toString()}
    })
  }
}
</script>

 

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐