废话少说,直接上最新鲜的干货
当然,你得提前安装好bootstrap,router,element-ui,vue-axios
1.上递归组件,此处参考了某位大神的代码,具体不知道是谁,因为到处都有人用
<template> <div> <template v-for='menu in menuList'> <!-- 如果当前有子菜单,则显示 el-submenu ,在el-subment 里调用 递归组件 --> <el-submenu v-if='menu.children.length>0' :index='menu.name' :key="menu.id" > <template slot="title" > <i :class="menu.icon"></i> {{menu.name}} </template> <!-- 调用自身 此处是重点--> <MenuTree :menuList='menu.children'></MenuTree> </el-submenu> <!-- 如果没有子菜单,则显示当前内容 --> <el-menu-item v-else :index='menu.url' :key='menu.id' > <i :class="menu.icon"></i> {{menu.name}} </el-menu-item> </template> </div> </template> <script> export default { name: "MenuTree", props: { menuList: { type: Array, required: false } } } </script> <style scoped> </style>
2.子组件菜单(Menus)
<template> <el-scrollbar wrap-class="scrollbar-wrapper"> <el-menu router mode="vertical" background-color="#551A8B" text-color="#FFFFFF" active-text-color="#409EFF" v-if="menuList" > <!-- <sidebar-item v-for="menu in menuList" :key="menu.id" :item="menu" />--> <MenuTree :menuList="menuList"></MenuTree> </el-menu> </el-scrollbar> </template> <script> import MenuTree from "./MenuTree"; export default { name:'Menus', components: { MenuTree, }, props:{ menuList: { type: Array, required: false } } } </script> <style > a { display: inline-block; width: 100%; overflow: hidden; } .el-menu { border: none; height: 100%; width: 100% !important; } .is-active > .el-submenu__title{ color: #f4f4f5!important; } </style>
3.父组件(App.Vue)引用
<template> <el-container> <el-header> XXXXXX </el-header> <el-container> <el-aside > <Menus :menuList="menuList"></Menus> </el-aside> <el-main> <router-view></router-view> </el-main> </el-container> </el-container> </template> <script> import Menus from "./views/Menus"; export default { name: 'app', components: { Menus, }, props: { menuList: { type: Array, required: false } }, mounted(){ this.axios.get('/menu/list') .then(resp => { this.menuList = resp.data.menuList; }) } } </script> <style> .el-header { background-color: #0000AA; color: #ffffff; line-height: 60px; font-size: 28px; } .el-aside { background-color: #e3e3e3; width: 200px !important; } body .el-table th.gutter{ display: table-cell!important; } body .el-table colgroup.gutter { display: table-cell !important; } </style>
4.总结
递归组件得重中之重,父组件与子组件、递归组件中都有共同的props,传值的过程:父组件menuList --> 菜单组件menuList --> 递归组件使用menuList