如何阻止v-autocomplete失去焦点时删除非选项文本?
解决Vuetify v2.x v-autocomplete失焦清除自定义输入的问题
在Vuetify v2.x中,v-autocomplete默认会在输入内容不在选项列表且组件失焦时自动清除输入,以下是两种可行的解决方法:
方法1:监听输入与失焦事件手动保留内容
通过监听输入事件记录用户的原始输入,在失焦时如果组件清空了绑定值,就将原始输入赋值回去,确保自定义内容不会丢失。
<div id="app"> <v-app> <v-main> <v-container> <v-autocomplete :items="items" label="Select an item" v-model="selectedItem" @input="handleInput" @blur="handleBlur" ></v-autocomplete> </v-container> </v-main> </v-app> </div>
// Uses vuetify v2.x new Vue({ el: '#app', vuetify: new Vuetify(), data: () => ({ items: ['foo', 'bar', 'baz', 'lorem', 'ipsum', 'something', 'else', 'to', 'make', 'itemlist', 'long'], selectedItem: null, userInput: '' }), methods: { handleInput(val) { this.userInput = val; }, handleBlur() { if (this.selectedItem === null) { this.selectedItem = this.userInput; } } } })
方法2:自定义过滤逻辑允许任意输入
设置一个始终返回true的过滤函数,让组件认为所有输入内容都是合法选项,从而不会在失焦时清除内容。
<div id="app"> <v-app> <v-main> <v-container> <v-autocomplete :items="items" label="Select an item" v-model="selectedItem" :filter="() => true" ></v-autocomplete> </v-container> </v-main> </v-app> </div>
// Uses vuetify v2.x new Vue({ el: '#app', vuetify: new Vuetify(), data: () => ({ items: ['foo', 'bar', 'baz', 'lorem', 'ipsum', 'something', 'else', 'to', 'make', 'itemlist', 'long'], selectedItem: null }) })
补充说明
- 方法2会让下拉列表始终显示所有选项,因为过滤逻辑不做筛选;如果需要保留正常的选项过滤同时支持自由输入,推荐使用方法1。
- 如果需要将用户的自定义输入添加到选项列表中,可以在
blur事件中判断内容不在items数组时,手动将其添加进去。
内容的提问来源于stack exchange,提问作者baceeeee
相关产品推荐
相关产品推荐

