直接贴代码
父组件
<template>
<el-menu
:default-active="this.$route.path" exact
class="el-menu-vertical-demo"
background-color="#324157"
text-color="#BFCBD9"
active-text-color="#20A0FF"
:collapse="isFlag"
router
popper-append-to-body=true
>
<!--将子菜单抽取出来,做为一个子组件-->
<nav-menu-item v-for="(item,index) in menuData" :key="index" :datas="item"/>
</el-menu>
</template>
<script>
import NavMenuItem from './NavMenuItem.vue';
export default {
components:{
NavMenuItem
},
data() {
return {
//伪造的数据,通过判断child属性有没有子菜单
menuData: [
{
url: "/mymsg",
icon: "el-icon-s-home",
name: "系统首页",
},
{
url: "",
icon: "el-icon-menu",
name: "鲜花管理",
child: [
{
url: "/flowerUp",
icon: "",
name: "鲜花上架",
},
{
url: "/flowerDown",
icon: "",
name: "鲜花下架",
},
],
},
{
url: "/user",
icon: "el-icon-setting",
name: "用户管理"
},
{
url:"/chart",
icon:"el-icon-pie-chart",
name:"销售统计"
}
],
};
},
props: ["isFlag"],
};
</script>
子组件
子组件通过v-if判断数据是否含child的属性。有则说明是二级菜单,没有则说明是一级菜单。多级菜单通过递归调用组件本身
<template>
<fragment>
<!-- 一级菜单 -->
<el-menu-item v-if="!datas.child" :index="datas.url">
<i :class="datas.icon"></i>
<span slot="title">{{datas.name}}</span>
</el-menu-item>
<!-- 二级菜单 -->
<el-submenu :index="datas.url" v-else >
<template slot="title">
<i :class="datas.icon"></i>
<span>{{datas.name}}</span>
</template>
<!-- 多级菜单 -->
<nav-menu-item v-for="(child,i ) in datas.child" :datas="child" :key="i"/>
</el-submenu>
</fragment>
</template>
<script>
export default {
name:"NavMenuItem",
//接收父组件传递的数据,进行渲染
props:["datas"]
};
</script>
注意:在调用组件本身实现多级菜单时,要注意v-for循环的对象,以及v-bind绑定时的属性
网友评论