vue中的菜单组件
在components中分别创建4个组件
Menu、 MenuItem、 ReSubMenu、 SubMenu
// Menu.vue代码 <template> <ul> <slot></slot> </ul> </template> <script> export default { name: "Menu" } </script>
// MenuItem.vue <template> <li> <slot></slot> </li> </template> <script> export default { name: "MenuItem" } </script>
// ReSubMenu.vue <template> <SubMenu> <template #title> {{data.title}} </template> <template v-for="child in data.children"> <MenuItem :key="child.title" v-if="!child.children"> {{child.title}} </MenuItem> <ReSubMenu :key="child.title" v-else :data="child"></ReSubMenu> </template> </SubMenu> </template> <script> import SubMenu from "./SubMenu" import MenuItem from "./MenuItem" export default { name: "ReSubMenu", props: { data: { type: Array, default: ()=>({}) } }, components: { SubMenu, MenuItem, } } </script>
// SubMenu.vue <template> <div> <div @click="click" > <slot name="title"></slot> </div> <div v-show="flag" class="sub"> <slot></slot> </div> </div> </template> <script> export default { name: "SubMenu", data(){ return { flag: false } }, methods: { click(){ this.flag = !this.flag } } } </script> <style scoped> .sub{ padding-left: 20px; } </style>
// App.vue <template> <div id="app"> <Menu> <template v-for="menu in menuList"> <MenuItem :key="menu.title" v-if="!menu.children">{{menu.title}}</MenuItem> <!-- 把重复的部分 先抽离出去 --> <ReSubMenu :key="menu.title" :data="menu" v-else></ReSubMenu> </template> </Menu> </div> </template> <script> import Menu from './components/Menu' import MenuItem from './components/MenuItem' import ReSubMenu from "./components/ReSubMenu" export default { name: 'App', data(){ return { menuList: [ { title: '菜单1', children: [ { title: '菜单1-1', children: [ { title: '菜单1-1-1', children: [ {title: '菜单1-1-1-1'}, {title: '菜单1-1-1-2'}, {title: '菜单1-1-1-3'}, ] }, { title: '菜单1-1-2' }, { title: '菜单1-1-3' } ] }, {title: '菜单1-2'}, {title: '菜单1-3'}, ] }, { title: '菜单2' }, { title: '菜单3' } ] } }, components: { Menu, MenuItem, ReSubMenu, } } </script> <style> #app { color: red; } </style>