Vuetify多选组件选中后能否按sort_order对选中项排序?
实现说明
该需求在Vuetify中完全可以实现。Vuetify的v-select多选组件的选中项渲染顺序和v-model绑定的数组顺序完全一致,只需调整选中数组的排序规则即可,不需要修改原有组件的插槽结构。
实现步骤
- 新增排序方法
在组件的methods中添加排序逻辑,对选中的数组按sort_order字段升序排列:
methods: { // 原有其他逻辑 sortSelectedObjectives() { // 先拷贝数组再排序后重新赋值,避免原地排序导致的响应式不生效问题,兼容Vue2/Vue3 this.record.objectives = [...this.record.objectives].sort((a, b) => a.sort_order - b.sort_order) } }
- 绑定排序触发时机
有两种触发方式可选,根据你的交互需求二选一即可:
- 每次选中/取消选中立即排序:给v-select添加
@change事件绑定 - 失焦后统一排序:把排序逻辑合并到原有
@blur事件中,避免打断用户选择过程
修改后的v-select代码示例:
<v-flex xs12> <v-tooltip :disabled="!showTooltip" top> <v-select slot="activator" class="objective-select" v-model="record.objectives" :items="objectiveArray" label="Objective(s)" placeholder="Enter Objective(s)" :error-messages="objectiveErrors" :return-object="true" item-text="objectiveDescription" multiple <!-- 二选一即可,不需要同时加 --> <!-- 方式1:每次选择变更就排序 --> @change="sortSelectedObjectives" <!-- 方式2:失焦后才排序 --> @blur="v.$each[index].objectives.$touch(); sortSelectedObjectives()" > <template v-slot:selection="{ item, index }"> <v-chip color="primary" dark class="objective-chip" :class="{ mobile:isMobile, tablet:isTablet }"> <span>{{ item.objectiveDescription }}</span> </v-chip> </template> </v-select> <span>Select one or more procedure objective(s)</span> </v-tooltip> </v-flex>
效果示例
- 多选组件界面

- 排序后选中效果

内容的提问来源于stack exchange,提问作者Jake Castillo
相关产品推荐
相关产品推荐

