使用多个v-list-group时无法控制展开状态的问题求助
实现v-list-group单展开(点击新组自动关闭已展开组)
要实现点击新的v-list-group时自动关闭其他已展开的组,核心是用一个变量统一管理当前展开的组标识,通过v-model绑定每个组的展开状态。具体实现步骤如下:
1. 新增状态变量
在组件的data中定义变量,用来存储当前展开组的唯一标识(这里用item.title作为标识,也可以替换为item.id这类更唯一的字段):
data() { return { expandedGroup: null // 初始无展开组 } }
2. 修改v-list-group绑定逻辑
给每个v-list-group绑定v-model控制展开状态,同时在激活器上添加点击事件更新展开标识:
v-model绑定为expandedGroup === item.title,确保只有匹配的组会展开- 在激活器的
v-list-item上添加@click事件,触发状态更新
修改后的完整代码:
<v-list class="pa-4" color="transparent" @click:select="customizer.handleSelect"> <!---Menu Loop ---> <template v-for="(item, i) in sidebarMenu" :key="i"> <!---Item Sub Header ---> <v-list-subheader v-if="item.header"> {{ item.header }} </v-list-subheader> <!---If Has Child ---> <v-list-group v-else-if="item.children" class="" :model-value="expandedGroup === item.title" @update:model-value="(val) => val && (expandedGroup = item.title)" > <!--- Inject Activator Template ---> <template #activator="{ props }"> <v-list-item v-bind="props" :value="item.title" rounded="lg" class="mb-1" @click="toggleGroup(item.title)" > <!--- Icon ---> <v-list-item-avatar start class="v-list-item-avatar--start"> <vue-feather :type="item.icon" class="feather-sm"></vue-feather> </v-list-item-avatar> <!--- Title ---> <v-list-item-title v-text="item.title" class="mr-auto"></v-list-item-title> <!-- Inject Append Template ---> <template #append> <v-list-item-avatar end class="v-list-item-avatar--end"> <vue-feather type="chevron-down" class="feather-sm"></vue-feather> </v-list-item-avatar> </template> </v-list-item> </template> <!--- v-list-item ---> <v-list-item v-for="(subitem, i) in item.children" :key="i" :value="subitem.to" :to="subitem.to" rounded="lg" class="first-level-item mb-1"> <v-list-item-avatar start class="v-list-item-avatar--start"> <vue-feather type="disc" class="feather-sm"></vue-feather> </v-list-item-avatar> <v-list-item-title v-text="subitem.title"></v-list-item-title> </v-list-item> <!-- /v-list-item ---> </v-list-group> </template> </v-list>
3. 添加切换方法
在组件的methods中添加toggleGroup方法,处理展开/关闭的逻辑:
methods: { toggleGroup(title) { // 点击当前展开组则关闭,否则切换到目标组 this.expandedGroup = this.expandedGroup === title ? null : title } }
核心说明
v-list-group的model-value用于控制展开状态,通过和expandedGroup的比较,确保同一时间只有一个组处于展开状态- 点击激活器时更新
expandedGroup,实现点击新组自动关闭旧组、点击当前组则收起的效果
内容的提问来源于stack exchange,提问作者Cameron
相关产品推荐
相关产品推荐

