Vue 递归多级菜单
栏目: JavaScript · 发布时间: 6年前
内容简介::star:️ 更多前端技术和知识点,搜索订阅号考虑以下菜单数据:需要实现的效果:
Vue 递归多级菜单
:star:️ 更多前端技术和知识点,搜索订阅号 JS 菌 订阅
考虑以下菜单数据:
[
{
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 使用,递归操作部分的代码也可以单独提取出来
请关注我的订阅号,不定期推送有关 JS 的技术文章,只谈技术不谈八卦 :blush:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- Web contextMenu 右键菜单 2.1,支持二级菜单
- 微信公众号开发C#系列-8、自定义菜单及菜单响应事件的处理
- .net core3.1 abp动态菜单和动态权限(动态菜单实现和动态权限添加) (三)
- BottomNavigationBar 导航菜单
- Alain 菜单权限控制
- 大图背景悬停导航菜单
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Introduction to Programming in Java
Robert Sedgewick、Kevin Wayne / Addison-Wesley / 2007-7-27 / USD 89.00
By emphasizing the application of computer programming not only in success stories in the software industry but also in familiar scenarios in physical and biological science, engineering, and appli......一起来看看 《Introduction to Programming in Java》 这本书的介绍吧!