[vue]多级菜单的实现 - 飞鲸百科
飞鲸百科 · 分享生活点滴联系我们

[vue]多级菜单的实现

飞鲸百科 编程日记 2023-09-07

效果图:

效果说明:
点击父菜单,如果有子菜单就在其左侧显示出子菜单

思路:
通过递归的方式。

代码:
子组件 MenuItem

// 子组件代码
<template><li><span @click="toggle(model)"> {{ isFolder? "<" + model.menuName : model.menuName   }}</span><ul v-if="isFolder" v-show="open" style="position: absolute;left: -120px;top: 0px; width:100px; background-color: cadetblue;"><menuItems v-for="(item, index) in model.childTree" :model="item" :key="index"></menuItems></ul></li>
</template><script type="text/javascript">export default {// 组件递归必要条件,name属性,然后在标签就可以通过name直接使用自己name: 'menuItems',props: ['model',],data() {return {// 控制子列表的显示隐藏open: false}},computed: {// 是否还有子列表需要渲染,作为v-if的判断条件isFolder() {return this.model.childTree && this.model.childTree.length}},methods: {// 切换列表显示隐藏的方法toggle(mode) {if(this.isFolder) {this.open = !this.open}/* 			if(mode.id != undefined && this.open){this.open = false;} */},}}
</script>
<style scoped>ul,li {list-style: none;}
</style>

父组件调用子组件

<template><!--https://www.jb51.net/css/378895.html--><view><div style="position: absolute;left:400px;"><ul><menu-item v-for="(model, index) in list" :model="model" :key="index"></menu-item></ul></div></view></template><script>import MenuItem from "../../components/MenuItem.vue"export default {components:{MenuItem},computed:{},data() {return {list: [ // 将菜单数据传到菜单组件中就行了{"id": "1","menuName": "菜单1","childTree": [{"menuName": "项目进度","childTree": [{"menuName": "项目一","childTree": [{ "menuName": "详细信息" }]}]}, {"menuName": "任务安排"}]}, {"id": "2","menuName": "菜单2"}, {"id": "3","menuName": "菜单3"}]};},methods:{}}
</script><style>	ul,li{list-style: none !important;}
</style>

结语:
效果图中是将子菜单显示在父菜单的左侧,也可以直接通过把下面的样式删除,让子菜单显示子父菜单的右侧 

 

医院资讯