Vue Multiselect分组组件:子选项全选后如何隐藏对应空分组标签
解决方案
问题原因
你之前添加的!props.option.length判断不生效,是因为分组标签对应的props.option是Vue Multiselect自动生成的特殊对象,本身不存储子选项长度属性,也不会自动关联对应分组的剩余未选中子项统计结果。
推荐实现方案(数据源层面过滤,最彻底)
直接通过计算属性过滤掉所有子项已全部选中的空分组,从源头避免空分组标签生成,和你已开启的hide-selected配置逻辑完全兼容:
- 新增计算属性处理原始选项数据
computed: { filteredOptions() { const selectedList = this.values || [] return this.options .map(group => { // 筛选当前分组下未被选中的子项 const remainingOptions = group.datas.filter(item => { return !selectedList.some(selected => selected.label === item.label) }) // 仅保留还有未选中子项的分组 if (remainingOptions.length) { return { ...group, datas: remainingOptions } } return null }) .filter(Boolean) } }
- 修改组件绑定属性
把<multiselect>里的:options="options"替换为:options="filteredOptions"即可,空分组的整个li标签会直接不渲染,不需要额外处理插槽显示逻辑。
插槽隐藏方案(不修改数据源的备选实现)
如果不想改动原始选项数据源,可以通过方法判断分组剩余子项数量,在插槽内控制显示:
- 新增分组剩余子项判断方法
methods: { hasUnselectedItem(groupLabel) { const selectedList = this.values || [] const targetGroup = this.options.find(item => item.type === groupLabel) if (!targetGroup) return false // 统计当前分组未选中子项数量 const unselectedCount = targetGroup.datas.filter(item => { return !selectedList.some(selected => selected.label === item.label) }).length return unselectedCount > 0 } }
- 修改option插槽判断逻辑
<template slot="option" slot-scope="props"> <span v-if="props.option.$isLabel && hasUnselectedItem(props.option.$groupLabel)"> {{ props.option.$groupLabel }} </span> <span v-else-if="!props.option.$isLabel"> {{ props.option.label }} </span> </template>
内容的提问来源于stack exchange,提问作者Raphael Mercier
相关产品推荐
相关产品推荐

