vue-admin-template如何实现点击父级动态菜单,同父级菜单自动收缩
时间: 2023-10-12 16:13:06 浏览: 106
在 `vue-admin-template` 中,动态菜单的数据是通过 `router` 配置生成的。要实现点击父级动态菜单时同父级菜单自动收缩,可以在菜单组件中监听父级菜单的点击事件,在点击父级菜单时触发相应的方法来收缩同级菜单。
具体实现步骤如下:
1. 在 `src/layout/components/Sidebar/index.vue` 中找到菜单组件 `SidebarItem` ,并在 `SidebarItem` 组件中添加 `click` 事件监听器。
```html
<template>
<el-submenu v-if="item.children && item.children.length > 0" :index="item.path">
<template slot="title">
<i :class="`iconfont ${item.meta.icon}`"></i>
<span slot="title">{{ item.meta.title }}</span>
</template>
<sidebar-item
v-for="(child, index) in item.children"
:key="index"
:item="child"
:parent-path="item.path"
:router="router"
:opened="openedMenus.includes(item.path)"
@click.native="handleClick" // 添加 click 事件监听器
></sidebar-item>
</el-submenu>
<el-menu-item v-else :index="item.path">
<router-link :to="item.path">
<i :class="`iconfont ${item.meta.icon}`"></i>
<span slot="title">{{ item.meta.title }}</span>
</router-link>
</el-menu-item>
</template>
<script>
export default {
name: "SidebarItem",
props: {
item: {
type: Object,
required: true,
},
parentPath: {
type: String,
default: "",
},
router: {
type: Object,
required: true,
},
opened: {
type: Boolean,
default: false,
},
},
data() {
return {
openedMenus: [], // 当前展开的菜单
};
},
mounted() {
this.handleOpenedMenus();
},
methods: {
handleClick() {
if (this.parentPath) {
// 如果有父级菜单,则收缩同级菜单
this.$emit("collapse", this.parentPath);
}
},
handleOpenedMenus() {
// 记录当前展开的菜单
if (this.opened && this.item.path) {
this.openedMenus.push(this.item.path);
}
},
},
};
</script>
```
2. 在 `Sidebar` 组件中监听 `SidebarItem` 组件的 `collapse` 事件,并在事件处理方法中更新当前展开的菜单列表。
```html
<template>
<el-menu
:default-active="$route.path"
class="sidebar-menu"
:collapse="isCollapse"
:unique-opened="true"
router
background-color="#304156"
text-color="#bfcbd9"
active-text-color="#409EFF"
>
<sidebar-item
v-for="(item, index) in sidebar"
:key="index"
:item="item"
:router="router"
:opened="openedMenus.includes(item.path)"
@collapse="handleCollapse" // 添加 collapse 事件监听器
></sidebar-item>
</el-menu>
</template>
<script>
import SidebarItem from "./SidebarItem";
export default {
name: "Sidebar",
components: {
SidebarItem,
},
props: {
sidebar: {
type: Array,
required: true,
},
isCollapse: {
type: Boolean,
default: false,
},
},
data() {
return {
openedMenus: [], // 当前展开的菜单
};
},
methods: {
handleCollapse(path) {
// 更新当前展开的菜单列表
if (this.openedMenus.includes(path)) {
this.openedMenus.splice(this.openedMenus.indexOf(path), 1);
} else {
this.openedMenus.push(path);
}
},
},
};
</script>
```
这样,点击父级动态菜单时,同级菜单就会自动收缩了。
阅读全文