ElementUI中el-select远程搜索 & 联想下拉功能优化

  • 需求:根据用户输入的最少四位编码,联想带出完整的编码值。
  • 思路:在编码的前四位发生变化时,才调用请求接口,避免实时请求编码数据(减少接口调用)。

模板部分

<template>
  <el-select
    v-model="value"
    multiple
    filterable
    remote
    reserve-keyword
    placeholder="请输入关键词"
    :remote-method="remoteMethod"
    :loading="loading"
    class="select-demo"
  >
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    >
    </el-option>
  </el-select>
</template>

js部分

export default {
  data() {
    return {
      options: [],
      value: [],
      rootVal: "",
      rootList: [],
      curPromise: null,
      loading: false,
      states: [
        "0110A",
        "0110B",
        "0110C",
        "0110D",
        "0120K",
        "0120",
        "0120D",
        "0980",
        "0980H",
        "0980O",
        "0980A",
        "0980C",
      ],
    };
  },
  methods: {
    // 设置并获取对应的下拉项
    getOptions(rootList, query) {
      return rootList
        .filter((item) => item.toUpperCase().startsWith(query))
        .map((item) => ({ value: item, label: item }));
    },
    // 模拟接口调用
    getData() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(
            this.states.filter((item) => item.toUpperCase().startsWith(this.rootVal))
          );
        }, 800);
      });
    },
    // request data
    async remoteMethod(query) {
      query = query.trim().toUpperCase();
      // 根据根查询
      if (query.length >= 4) {
        this.loading = true;
        // 收集/更新根
        if (!this.rootVal || !query.startsWith(this.rootVal)) {
          this.rootVal = query.slice(0, 4);
          this.rootList = [];
          this.curPromise = this.getData()
        }
        // 判断是否需要等待上一次最新的请求结果
        if (!this.rootList.length) {
          this.rootList = await this.curPromise;
        }
        this.options = this.getOptions(this.rootList, query);
        this.loading = false;
      } else {
        this.options = [];
      }
    },
  },
};

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值