最近公司需要动态生成侧边栏,所以就对这个东西进行了研究,发现可以使用递归组件来实现。UI 框架使用
element-ui
;
注意
递归的基本概念就没必要提了,注意要有中断的临界点。
前期准备
动态的生成侧边栏,需要约定一个数据格式,可以用来循环或者递归操作。现成的 Vue 的 VNode 就非常适合,所以我们可以模拟一个简化版的(好像和VNode差得有点远...)。
export default [
{
self: { index: "index", icon: "el-icon-odometer", title: "首页" },
child: []
},
{
self: {
index: "userlist",
icon: "el-icon-s-tools",
title: "用户权限"
},
child: [
{ self: { index: "user", icon: "", title: "用户管理" }, child: [] },
{
self: {
index: "usergroup",
icon: "",
title: "用户组管理"
},
child: []
},
{ self: { index: "role", icon: "", title: "角色管理" }, child: [] }
]
},
{
self: {
index: "pppp",
icon: "el-icon-s-management",
title: "票务管理"
},
child: [
{ self: { index: "", icon: "", title: "规则管理" }, child: [] },
{ self: { index: "", icon: "", title: "票种管理" }, child: [] }
]
},
{
self: {
index: "/user",
icon: "el-icon-s-ticket",
title: "售票管理"
},
child: [
{ self: { index: "", icon: "", title: "售票" }, child: [] },
{ self: { index: "", icon: "", title: "取票" }, child: [] },
{ self: { index: "", icon: "", title: "长期卡" }, child: [] },
{ self: { index: "", icon: "", title: "退票" }, child: [] }
]
},
]
了解Vue递归组件
传送门 在此,写的太过于简洁,对 Vue 组件了解不是太深入的估计不是太懂,我们先来一个Demo。
DEMO
简化版数据格式
list: [
{
name: "1",
child: [
{ name: "1-1", child: [] },
{ name: "1-2", child: [] },
{
name: "1-3",
child: [
{
name: "1-3-1",
child: [
{
name: "1-3-1-1"
}
]
},
{ name: "1-3-2", child: [] },
{ name: "1-3-3", child: [] }
]
}
]
},
{
name: "2",
child: [
{
name: "2-1",
child: []
}
]
}
]
childComponents
-
{{ item.name }}
引用
结果
渲染结果
注意
必须要给 component 定义 name,不然不能识别内部调用自身。
参考博客
https://blog.csdn.net/kcorih/article/details/100045888
开始自己的组件
我们首先可以参考下element-ui
的相关组件文档:
https://element.eleme.cn/#/en-US/component/menu
代码如下
{{ item.self.title }}
{{ item.self.title }}
比较不舒服的是(ESlint校验太严格了吧), .vue
文件的 template
下必须有是一个根标签。所以多了一个div
标签,每有一个child
数组就会渲染一次这个组件。
把它放入 Menu 中
效果
效果图
不足之处
- 没有对标签进行分组(主要是我们没有需求...);
- 多了一个
div
标签; - 可能存在性能问题(需要验证);
以上仅为个人愚见,有错误或者不足的恳请联系改正。
PS:感觉没有React写着优雅,一般嵌套也就三到四层。