Vue递归菜单
一、效果图:
二、代码(Vue Cli 快速原型开发)
App.vue
1 <template> 2 <div id="app"> 3 <template v-for="item in menus"> 4 <!--没有子菜单的直接渲染title --> 5 <Menu :key="item.title" v-if="(item.children.length==0)"> 6 <li class="title">{{item.title}}</li> 7 </Menu> 8 <!--这里还在v-for循环中,在向ReMenu子组件中传递数据是可以绑定item(分别表示menus的三个对象元素) --> 9 10 <!-- 有子菜单的部分--> 11 <ReMenu v-else :item="item"></ReMenu> 12 </template> 13 </div> 14 15 </template> 16 17 <script> 18 import Menu from './Menu.vue' 19 import ReMenu from './ReMenu.vue' 20 export default { 21 name: 'app', 22 components: { 23 Menu, 24 ReMenu 25 }, 26 data() { 27 return { 28 msg: "递归菜单", 29 menus: [{ 30 "path": "/func1", 31 "title": "功能1", 32 "children": [{ 33 "title": "功能1-1", 34 "children": [{ 35 "title": "功能1-1-1", 36 "children": [{ 37 "title": "功能1-1-1-1", 38 "children": [] 39 }, 40 { 41 "title": "功能1-1-1-2", 42 "children": [] 43 }, { 44 "title": "功能1-1-1-3", 45 "children": [] 46 }, 47 ] 48 }, 49 { 50 "title": "功能1-1-2", 51 "children": [] 52 }, { 53 "title": "功能1-1-3", 54 "children": [] 55 }, 56 ] 57 }, { 58 "title": "功能1-2", 59 "children": [] 60 }, { 61 "title": "功能1-3", 62 "children": [] 63 }, ] 64 }, 65 { 66 "title": "功能2", 67 "children": [{ 68 "title": "功能2-1", 69 "children": [] 70 }, { 71 "title": "功能2-2", 72 "children": [] 73 }, { 74 "title": "功能2-3", 75 "children": [] 76 }, ] 77 }, 78 { 79 "title": "功能3", 80 "children": [{ 81 "title": "功能3-1", 82 "children": [] 83 }, { 84 "title": "功能3-2", 85 "children": [] 86 }, { 87 "title": "功能3-3", 88 "children": [{ 89 "title": "功能3-3-1", 90 "children": [] 91 }, { 92 "title": "功能3-3-2", 93 "children": [] 94 }, { 95 "title": "功能3-3-3", 96 "children": [] 97 }] 98 }, ] 99 }, 100 { 101 "title": "功能4", 102 "children": [] 103 } 104 ] 105 } 106 }, 107 } 108 </script>
Menu.App
1 <template> 2 <ul> 3 <slot></slot> 4 </ul> 5 </template> 6 7 <script> 8 export default { 9 name: "Menu", 10 props: ["msg","menus"] 11 } 12 </script>
MenuItem.app
1 <template> 2 <ul> 3 <li @click="change" class="title"> 4 <slot name="title">默认值</slot> 5 </li> 6 7 <li v-show="flag" style="list-style:none"> 8 <slot name="content">默认值</slot> 9 </li> 10 </ul> 11 </template> 12 13 <script> 14 export default { 15 name: "MenuItem", 16 data() { 17 return { 18 flag:false 19 } 20 }, 21 methods: { 22 change(){ 23 this.flag=!this.flag 24 } 25 }, 26 } 27 </script> 28 29 <style > 30 .title{ 31 cursor:pointer; 32 } 33 </style>
Remenu.Vue
1 <template> 2 <MenuItem> 3 <template v-slot:title> 4 <li :key="item.title">{{item.title}}</li> 5 </template> 6 7 <template v-slot:content> 8 <ul v-for="child in item.children" v-if="(child.children.length==0)">{{child.title}}</ul> 9 <ReMenu v-else :item="child"></ReMenu> 10 </template> 11 </MenuItem> 12 13 </template> 14 <script> 15 import MenuItem from './MenuItem.vue' 16 export default { 17 // mounted() { 18 // console.log(this.item) 19 // }, 20 name: "ReMenu", 21 components: { 22 MenuItem, 23 }, 24 props: ["item"] 25 } 26 </script>