目录
一、获取左侧菜单数据
后端接口:
前端页面:
① 页面加载后显示,调用 created 生命周期
created() {
this.getMenuList()
},
② 在 methods 中,定义相关函数 (getMenuList)
// 获取所有的菜单
async getMenuList() {
const {data:res} = await this.$http.get('menus')
if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
this.menulist = res.data
console.log(res)
}
③ 在data中,挂载变量
data() {
return {
// 左侧菜单数据
menulist: []
}
},
二、通过双层for循环渲染左侧菜单
<!--一级菜单-->
<!--数值和字符串拼接变成字符串-->
<el-submenu :index="item.id + '' "
v-for="item in menulist"
key="item.id">
<!--一级菜单的模板区-->
<template slot="title">
<!--图标-->
<i class="el-icon-location"></i>
<!--文本-->
<span>{{ item.authName }}</span>
</template>
<!--二级菜单-->
<el-menu-item :index="subItem.id + '' "
v-for="subItem in item.children"
:key="subItem.id">
<template slot="title">
<!--图标-->
<i class="el-icon-location"></i>
<!--文本-->
<span>{{ subItem.authName }}</span>
</template>
</el-menu-item>
</el-submenu>
</el-menu>
三、页面代码
<template>
<el-container class="home-container">
<!--头部区域-->
<el-header>
<div>
<img src="@/assets/ashsh.png" alt="" style="height: 60px;width: 60px">
<span>电商后台管理系统</span>
</div>
<el-button type="info" @click="logout">退出</el-button>
</el-header>
<!--页面主体区域-->
<el-container>
<!--侧边栏-->
<el-aside width="200px">
<!--侧边栏菜单区域-->
<el-menu background-color="#333744"
text-color="#fff"
active-text-color="#409EFF">
<!--一级菜单-->
<!--数值和字符串拼接变成字符串-->
<el-submenu :index="item.id + ''" v-for="item in menulist" key="item.id">
<!--一级菜单的模板区-->
<template slot="title">
<!--图标-->
<i class="el-icon-location"></i>
<!--文本-->
<span>{{ item.authName }}</span>
</template>
<!--二级菜单-->
<el-menu-item :index="subItem.id + '' "
v-for="subItem in item.children"
:key="subItem.id">
<template slot="title">
<!--图标-->
<i class="el-icon-menu"></i>
<!--文本-->
<span>{{ subItem.authName }}</span>
</template>
</el-menu-item>
</el-submenu>
</el-menu>
</el-aside>
<!-- 右侧内容主体-->
<el-main>Main</el-main>
</el-container>
</el-container>
</template>
<script>
export default {
name: "Home",
data() {
return {
// 左侧菜单数据
menulist: []
}
},
created() {
this.getMenuList()
},
methods: {
logout() {
window.sessionStorage.clear();
this.$router.push('/login');
},
// 获取所有的菜单
async getMenuList() {
const {data:res} = await this.$http.get('menus')
if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
this.menulist = res.data
console.log(res)
}
}
}
</script>
<style scoped lang="less">
.home-container {
height: 100%;
}
.el-header {
background-color: #373D41;
display: flex;
justify-content: space-between;
padding-left: 0;
align-items: center; // 按钮居中
color: #fff;
font-size: 20px;
> div {
display: flex;
align-items: center;
span {
margin-left: 15px;
}
}
}
.el-aside {
background-color: #333744;
}
.el-main {
background-color: #EAEDF1;
}
</style>
四、每次只能打开一个菜单项并解决边框问题
1. 每次只能打开一个菜单栏
在menu 标签中 加入 :unique-opened="true"
<el-menu background-color="#333744"
text-color="#fff"
active-text-color="#409EFF"
:unique-opened="true">
2. 解决边框问题
在对应的标签下,设置 border-right: none; 样式
.el-menu{
border-right: none;
}