Vuetify Combobox:输入时如何过滤并移除无效输入项
解决Vuetify Combobox禁止自定义输入的问题
要限制用户只能选择预设的propertyItems选项,避免随机输入按Tab后被存入组件,可以通过以下两种方案实现:
方案一:监听Tab键事件,拦截无效输入
给Combobox添加Tab键监听,判断当前输入内容是否在选项列表中,若不存在则阻止默认行为并清空输入:
<v-row class="ma-1"> <v-combobox v-model="selectedProperties" :items="propertyItems" label="Properties" :menu-props="{ maxHeight: 195 }" multiple chips closable-chips max-height="4" @keydown.tab="handleTabKey" ></v-combobox> </v-row>
对应的JS逻辑:
methods: { handleTabKey(e) { const inputValue = e.target.value.trim() const isItemExist = this.propertyItems.some(item => item === inputValue) if (!isItemExist && inputValue) { e.preventDefault() e.target.value = '' } } }
方案二:过滤v-model值,确保仅保留有效选项
如果担心用户通过粘贴等其他方式输入无效内容,可以监听selectedProperties,自动过滤掉不在选项列表中的值:
watch: { selectedProperties(newVal) { this.selectedProperties = newVal.filter(item => this.propertyItems.includes(item)) } }
两种方案可结合使用,既拦截Tab键的无效输入,又确保最终存入组件的都是合法选项。
内容的提问来源于stack exchange,提问作者Prathik Anand
相关产品推荐
相关产品推荐

