输出代码vue使用element ui 的导航组件实现点击头部一级菜单,侧边栏展示一级菜单下的子菜单,刷新页面时侧边栏菜单数据不丢失
时间: 2024-03-08 13:47:52 浏览: 69
基于vue.js实现侧边菜单栏
下面是一个简单的示例代码,实现了使用 Element UI 的导航组件实现点击头部一级菜单,侧边栏展示一级菜单下的子菜单,刷新页面时侧边栏菜单数据不丢失:
```html
<template>
<div>
<el-container>
<el-header>
<el-menu :default-active="$route.path" mode="horizontal" @select="handleMenuSelect">
<el-submenu index="1">
<template slot="title">一级菜单1</template>
<el-menu-item index="/sub-menu-1">子菜单1</el-menu-item>
<el-menu-item index="/sub-menu-2">子菜单2</el-menu-item>
</el-submenu>
<el-submenu index="2">
<template slot="title">一级菜单2</template>
<el-menu-item index="/sub-menu-3">子菜单3</el-menu-item>
<el-menu-item index="/sub-menu-4">子菜单4</el-menu-item>
</el-submenu>
</el-menu>
</el-header>
<el-container>
<el-aside>
<el-menu :default-openeds="openeds" :default-active="$route.path" class="el-menu-vertical-demo" @select="handleSubMenuSelect">
<el-submenu v-for="item in subMenus" :key="item.index" :index="item.index">
<template slot="title">{{ item.title }}</template>
<el-menu-item v-for="subItem in item.subMenus" :key="subItem.index" :index="subItem.index">{{ subItem.title }}</el-menu-item>
</el-submenu>
</el-menu>
</el-aside>
<el-main>Main</el-main>
</el-container>
</el-container>
</div>
</template>
<script>
import { mapState } from 'vuex';
export default {
data() {
return {
subMenus: [],
openeds: [],
};
},
computed: {
...mapState({
menuData: state => state.menuData,
}),
},
created() {
this.setSubMenus(this.$route.path);
},
methods: {
handleMenuSelect(index) {
this.$router.push(index);
this.setSubMenus(index);
},
handleSubMenuSelect(index) {
this.$router.push(index);
},
setSubMenus(path) {
const menu = this.menuData.find(item => item.index === path);
if (menu) {
this.subMenus = menu.subMenus;
this.openeds = [menu.index];
} else {
this.subMenus = [];
this.openeds = [];
}
},
},
};
</script>
```
这个示例代码中使用了 Vuex 存储了菜单数据,点击头部一级菜单时根据路由跳转和当前路由路径设置侧边栏的子菜单和展开的一级菜单。这样在刷新页面时,侧边栏菜单数据不会丢失。
阅读全文