el-select远程搜索

唐烨煜
2023-12-01
//远程搜素
<el-select
        v-model="userName"
        filterable
        remote
        :remote-method="remoteMethod"
        :loading="loading"
        @change="selectChanged"
        clearable
        :disabled="disabled" 
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
</el-select>

<script>
export default {
  data() {
    return {
      options: [], //选项
      loading: false,
      list: [], //筛选后的可选项
    };
  },
	methods: {
        //筛选
		async remoteMethod(query) {
       		if (query !== "") {
             this.loading = true;
             let { data } = await getProfess(query);
             this.list = data.map((item) => {
               return {
                 value: `${item.userId}`,
                 label: `${item.userName}`,
               };
             });
             setTimeout(() => {
               this.loading = false;
               this.options = this.list.filter((item) => {
                 return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
               });
             }, 200);
          } else {
             this.options = [];
            }
     },
    // 选中后的处理
    selectChanged(params) {
        console.log(params)
    },   
        }
    }
</script>

上面那个会进行实时搜素,后端大哥说不要一直搜等用户输入完成后点击回车再进行搜索就有了下面这个

//点击回车后再进行搜素
<el-select
        v-model="userName"
        filterable
        remote
        :remote-method="remoteMethods"
        :loading="loading"
        @change="selectChanged"
        clearable
        :disabled="disabled"
        @keydown.enter.native="remoteMethod"  
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
</el-select>
<script>
export default {
  data() {
    return {
      options: [], //选项
      loading: false,
      list: [], //筛选后的可选项
      remoteSearchQuery: ''
    };
  },
	methods: {
        remoteMethods(query){
          this.remoteSearchQuery = query
        },
        //筛选
		async remoteMethod() {
       		if (this.remoteSearchQuery !== "") {
             this.loading = true;
             let { data } = await getProfess(this.remoteSearchQuery);
             this.list = data.map((item) => {
               return {
                 value: `${item.userId}`,
                 label: `${item.userName}`,
               };
             });
             setTimeout(() => {
               this.loading = false;
               this.options = this.list.filter((item) => {
                 return item.label.toLowerCase().
                 indexOf(this.remoteSearchQuery.toLowerCase()) > -1;
               });
             }, 200);
          } else {
             this.options = [];
            }
     },
    // 选中后的处理
    	selectChanged(params) {
        	console.log(params)
    	},   
    }
}
</script>
 类似资料: