您的位置:首页 > Web前端 > Vue.js

Vue 递归多级菜单的实例代码

2019-05-05 08:40 302 查看

考虑以下菜单数据:

[
{
name: "About",
path: "/about",
children: [
{
name: "About US",
path: "/about/us"
},
{
name: "About Comp",
path: "/about/company",
children: [
{
name: "About Comp A",
path: "/about/company/A",
children: [
{
name: "About Comp A 1",
path: "/about/company/A/1"
}
]
}
]
}
]
},
{
name: "Link",
path: "/link"
}
];

需要实现的效果:

 

首先创建两个组件 Menu 和 MenuItem

// Menuitem

<template>
<li class="item">
<slot />
</li>
</template>

MenuItem 是一个 li 标签和 slot 插槽,允许往里头加入各种元素

<!-- Menu -->

<template>
<ul class="wrapper">
<!-- 遍历 router 菜单数据 -->
<menuitem :key="index" v-for="(item, index) in router">
<!-- 对于没有 children 子菜单的 item -->
<span class="item-title" v-if="!item.children">{{item.name}}</span>

<!-- 对于有 children 子菜单的 item -->
<template v-else>
<span @click="handleToggleShow">{{item.name}}</span>
<!-- 递归操作 -->
<menu :router="item.children" v-if="toggleShow"></menu>
</template>
</menuitem>
</ul>
</template>

<script>
import MenuItem from "./MenuItem";

export default {
name: "Menu",
props: ["router"], // Menu 组件接受一个 router 作为菜单数据
components: { MenuItem },
data() {
return {
toggleShow: false // toggle 状态
};
},
methods: {
handleToggleShow() {
// 处理 toggle 状态的是否展开子菜单 handler
this.toggleShow = !this.toggleShow;
}
}
};
</script>

Menu 组件外层是一个 ul 标签,内部是 vFor 遍历生成的 MenuItem

这里有两种情况需要做判断,一种是 item 没有 children 属性,直接在 MenuItem 的插槽加入一个 span 元素渲染 item 的 title 即可;另一种是包含了 children 属性的 item 这种情况下,不仅需要渲染 title 还需要再次引入 Menu 做递归操作,将 item.children 作为路由传入到 router prop

最后在项目中使用:

<template>
<div class="home">
<menu :router="router"></menu>
</div>
</template>

<script>
import Menu from '@/components/Menu.vue'

export default {
name: 'home',
components: {
Menu
},
data () {
return {
router: // ... 省略菜单数据
}
}
}
</script>

最后增加一些样式:

MenuItem:

<style lang="stylus" scoped>
.item {
margin: 10px 0;
padding: 0 10px;
border-radius: 4px;
list-style: none;
background: skyblue;
color: #fff;
}
</style>

Menu:

<style lang="stylus" scoped>
.wrapper {
cursor: pointer;

.item-title {
font-size: 16px;
}
}
</style>

Menu 中 ul 标签内的代码可以单独提取出来,Menu 作为 wrapper 使用,递归操作部分的代码也可以单独提取出来

总结

以上所述是小编给大家介绍的Vue 递归多级菜单的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Vue 递归 多级 菜单