You need to enable JavaScript to run this app. Vuetify v-autocomplete如何自定义过滤器实现同时匹配对象Key和Value
优惠活动
大模型
产品
解决方案
定价
更多

Vuetify v-autocomplete如何自定义过滤器实现同时匹配对象Key和Value

解决方案

Vuetify 的 v-autocomplete 组件支持通过自定义过滤规则实现多字段匹配,操作步骤如下:

步骤1:定义自定义过滤方法

在你的 Vue 实例的 methods 中新增匹配逻辑,同时校验Key和Value两个字段是否包含搜索关键词:

methods: {
  customFilter (item, queryText) {
    const searchKey = queryText.trim().toLowerCase()
    // 数字类型Key先转字符串,统一不区分大小写匹配
    const matchKey = item.Key.toString().toLowerCase().includes(searchKey)
    const matchValue = item.Value.toLowerCase().includes(searchKey)
    return matchKey || matchValue
  }
}

步骤2:给v-autocomplete绑定过滤方法

在原有组件代码上新增:filter属性,绑定你定义的过滤方法即可:

<v-autocomplete
  label="Trading Partner"
  v-model="tradingPartner"
  :items="tradingpartners"
  item-value="Key"
  item-text="Value"
  return-object
  :filter="customFilter"
>
  <template slot="selection" slot-scope="{ item }">
    {{ item.Key }} - {{ item.Value }}
  </template>
  <template slot="item" slot-scope="{ item }">
    {{ item.Key }} - {{ item.Value }}
  </template>
</v-autocomplete>

补充说明

如果不想新增过滤方法,也可以选择预处理tradingpartners数组,给每个元素新增一个Key + Value拼接后的字段,再把item-text属性指向这个拼接字段,即可实现默认搜索同时匹配两个字段的效果。如果你的项目使用的是Vuetify 3,仅需要将插槽写法调整为v-slot:selection和v-slot:item的形式,核心的过滤逻辑保持不变。

内容的提问来源于stack exchange,提问作者Francois Taljaard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 09:15:07