Vuetify(Vue2) v-select选中后所有项显示active的问题
问题描述
使用Vuetify(Vue 2.x)开发v-select组件时,选中任意选项后,所有选项都会显示为active状态,而非仅选中项高亮。
组件代码:
<v-select v-model="mail" :items="mails" dense clearable chips menu-props="auto" label="..." @change="..." prepend-icon="mdi-email-check"> <template slot="selection" slot-scope="data"> <v-chip small color="primary" text-color="white">{{data.item.dt_local}}</v-chip> </template> <template slot="item" slot-scope="data"> <v-list-item-avatar> <v-icon>mdi-timeline-clock-outline</v-icon> </v-list-item-avatar> <v-list-item-content> <span v-if="data.item.subject == null">Aucun objet</span> <span v-else>{{ data.item.subject }}</span> <v-list-item-title>{{ data.item.dt_local }}</v-list-item-title> </v-list-item-content> </template> </v-select>
示例数据:
this.mails = [ { "subject": "Factures", "dt_local": "2022-12-03 09:54:48", }, { "subject": "Factures", "dt_local": "2022-12-03 09:39:39", }, { "subject": null, "dt_local": "2022-12-02 19:27:28", } ]
问题原因
Vuetify的v-select默认使用浅比较判断选项是否为选中项。当多个选项对象存在重复属性(比如前两项的subject值相同),且没有指定唯一标识字段时,组件无法精准区分选中项,导致所有匹配部分属性的选项都被标记为active。
解决方案
给v-select添加item-value属性,指定数据中唯一的字段作为选项标识(这里dt_local每个值都是唯一的,适合作为标识),让组件能准确匹配选中项:
修改后的组件代码:
<v-select v-model="mail" :items="mails" dense clearable chips menu-props="auto" label="..." @change="..." prepend-icon="mdi-email-check" item-value="dt_local"> <!-- 新增唯一标识配置 --> <template slot="selection" slot-scope="data"> <v-chip small color="primary" text-color="white">{{data.item.dt_local}}</v-chip> </template> <template slot="item" slot-scope="data"> <v-list-item-avatar> <v-icon>mdi-timeline-clock-outline</v-icon> </v-list-item-avatar> <v-list-item-content> <span v-if="data.item.subject == null">Aucun objet</span> <span v-else>{{ data.item.subject }}</span> <v-list-item-title>{{ data.item.dt_local }}</v-list-item-title> </v-list-item-content> </template> </v-select>
如果数据中有专门的唯一ID字段(比如id),优先使用item-value="id",更符合通用规范。
内容的提问来源于stack exchange,提问作者orville
相关产品推荐
相关产品推荐

