ElementUI 下拉选择器的远程搜索输入空格不触发remoteMethod方法--优化

远程搜索功能:

trim()方法去除query的首尾空格。


优化原因:

当在输入框中打入空格依然回去调用接口,优化可以发起调用接口的请求


优化代码:

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

<script>
export default {
  data () {
    return {
      options: [],
      value: [],
      list: [],
      loading: false,
      states: ['李白', '王勃', '白居易']
    }
  },
  mounted () {
    this.list = this.states.map(item => {
      return { value: `value:${item}`, label: `label:${item}` }
    })
  },
  methods: {
    remoteMethod (query) {
      const data = query.trim()
      if (data !== '') {
        console.log('输入非空格才会执行此语句' + 123456)
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.options = this.list.filter(item => {
            return item.label.toLowerCase()
              .indexOf(data.toLowerCase()) > -1
          })
        }, 200)
      } else {
        this.options = []
      }
    }
  }
}
</script>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
在 Element UI 的 select 组件中,可以通过设置 `filterable` 属性和 `remote` 属性来实现联动查询后台接口的功能。具体实现步骤如下: 1. 设置 `filterable` 属性为 `true`,表示需要启用搜索功能。 2. 设置 `remote` 属性为 `true`,表示需要从后台接口获取选项列表。 3. 设置 `remote-method` 属性为一个函数,该函数会在搜索时被调用,可以在该函数中发送请求获取符合条件的选项列表。 以下是一个示例代码: ```html <el-select v-model="value" filterable remote :remote-method="remoteMethod" :loading="loading"> <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option> </el-select> ``` ```js export default { data() { return { value: '', options: [], loading: false } }, methods: { remoteMethod(query) { this.loading = true; // 发送请求获取选项列表 axios.get('/api/selectOptions', { params: { q: query } }).then(res => { this.options = res.data; this.loading = false; }).catch(error => { console.log(error); this.loading = false; }); } } } ``` 在上述代码中,`remoteMethod` 函数会在搜索时被调用,使用 axios 库发送请求到 `/api/selectOptions` 接口,并将搜索关键字作为 `q` 参数发送。后端接口需要根据关键字返回符合条件的选项列表。获取到选项列表后,将其赋值给 `options` 变量,即可在 select 组件中显示出来。同时,为了提高用户体验,可以设置 `loading` 属性为 `true`,表示正在加载选项列表,加载完成后再将其设置为 `false`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值