You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让v-autocomplete组件支持绑定不在items列表内的自定义输入值

实现方案

第一步:修改v-autocomplete组件属性

核心是添加allow-custom-values属性,这个属性允许组件接受不在items列表内的自定义输入值。同时因为你的items是纯数字数组,不需要返回对象可以删掉return-object属性,避免不必要的类型报错。
修改后的组件代码:

<v-autocomplete
  v-model="fromPrice"
  :items="listOfFromItems"
  dense
  solo
  label="from"
  hide-details
  color="red darken-1"
  allow-custom-values
  type="number"
/>

这里额外加了type="number"限制只能输入数字,避免用户输入非数值内容。

第二步:处理自定义值的类型转换

allow-custom-values返回的自定义输入默认是字符串类型,如果你需要的是数值类型,可以加监听做转换:

Vue2选项式API写法

watch: {
  fromPrice(newVal) {
    if (typeof newVal === 'string') {
      this.fromPrice = Number(newVal) || 0
    }
  }
}

Vue3组合式API写法

const fromPrice = ref('')
watch(fromPrice, (newVal) => {
  if (typeof newVal === 'string') {
    fromPrice.value = Number(newVal) || 0
  }
})

第三步(可选):优化items生成逻辑

你原来的items生成代码可以简化,避免频繁展开数组造成的性能损耗:

this.listOfFromItems = Array.from({length: 101}, (_, i) => i * 50)
// 直接生成0到5000步长50的数组,和你原来的循环效果一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:36:03