如何在Vuetify v-select中实现菜单与选中值显示不同内容?
解决v-select下拉显示全称+缩写,选中后仅显示缩写的问题
要实现这个需求,我们只需要调整v-select的核心属性并修正v-model的初始值格式,具体操作如下:
关键修改点
- 把
item-text改成函数形式:原来的item-text="state"只会展示州名,我们改成返回拼接后的字符串,让下拉选项显示「州名, 缩写」的格式。 - 修正v-model初始值:因为
item-value="abbr",所以v-model应该存储缩写数组而非对象数组,这样选中后才会直接显示缩写。 - 保留
item-value="abbr"不变,确保选中后的值是缩写,同时多选模式下自动展示选中的缩写内容。
修改后的完整代码
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css" rel="stylesheet"/> <link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet"/> <script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script> <div id="app"> <v-app id="inspire"> <v-container fluid> <v-row align="center"> <v-col cols="6"> <v-subheader>Custom items</v-subheader> </v-col> <v-col cols="6"> <v-select v-model="select" :items="items" :item-text="item => `${item.state}, ${item.abbr}`" item-value="abbr" label="Select" persistent-hint multiple ></v-select> </v-col> </v-row> </v-container> </v-app> </div> <script> new Vue({ el: '#app', vuetify: new Vuetify(), data () { return { select: ['FL'], // 修正为缩写数组,与item-value对应 items: [ { state: 'Florida', abbr: 'FL' }, { state: 'Georgia', abbr: 'GA' }, { state: 'Nebraska', abbr: 'NE' }, { state: 'California', abbr: 'CA' }, { state: 'New York', abbr: 'NY' }, ], } }, }) </script>
效果说明
- 下拉菜单展开时,每个选项显示
Florida, FL这类完整格式,方便用户识别对应州。 - 选中选项后,输入框内仅展示对应的缩写(如
FL),保持界面简洁。 - 多选模式下,多个缩写会自动以逗号分隔展示,完全符合需求。
内容的提问来源于stack exchange,提问作者yukashima huksay
相关产品推荐
相关产品推荐

