组件递归
实现嵌套评论
实现多级菜单
树状数据展示
实现原理
sh
1. 父组件调用子组件,子组件调用自身
父组件
vue
<template>
<div>
<Child :dataList="dataList" />
</div>
</template>
<script>
// 引入数据文件
import dataTree from '@/data/树状数据';
// 引入递归组件
import Child from '@/components/递归组件/Child.vue';
export default {
components: {
Child,
},
data() {
return {
dataList: dataTree,
};
},
};
</script>
子组件
vue
<template>
<div class="child">
<div
v-for="(item, index) in dataList"
:key="index">
<p>编号:{{ item.id }}</p>
<p>姓名:{{ item.name }}</p>
<p>性别:{{ item.gender }}</p>
<!-- 递归引用 -->
<!-- 有 且 length不为空 才进行渲染-->
<Child
v-if="item.children && item.children.length > 0"
:dataList="item.children"
:name="item.id" />
</div>
</div>
</template>
<script>
import Child from '@/components/递归组件/Child.vue';
export default {
name: 'Child', // 设置组件名称 不设置会报错 名字要与 ==组件名相同==
components: {
Child, // 跟这个相同 ==组件名相同==
},
mounted() {
console.log('执行了');
},
// 获取传递的数据
props: {
dataList: Array,
},
};
</script>
<style scoped>
.child {
margin-left: 30px;
border-left: 4px solid #48b785;
}
</style>
效果图
测试的数据
json
[
{
"id": 1,
"name": "王小明",
"gender": "男",
"age": 35,
"children": [
{
"id": 2,
"name": "张美丽",
"gender": "女",
"age": 28,
"children": [
{
"id": 3,
"name": "李华",
"gender": "男",
"age": 5,
"children": []
},
{
"id": 4,
"name": "刘芳",
"gender": "女",
"age": 3,
"children": []
}
]
},
{
"id": 5,
"name": "赵强",
"gender": "男",
"age": 30,
"children": [
{
"id": 6,
"name": "孙丽娜",
"gender": "女",
"age": 1,
"children": []
}
]
}
]
},
{
"id": 7,
"name": "李华",
"gender": "男",
"age": 5,
"children": [
{
"id": 10,
"name": "赵强",
"gender": "男",
"age": 30,
"children": []
}
]
},
{
"id": 8,
"name": "孙丽娜",
"gender": "女",
"age": 1,
"children": [
{
"id": 11,
"name": "赵子强",
"gender": "男",
"age": 30,
"children": [
{
"id": 12,
"name": "孙丽",
"gender": "女",
"age": 1,
"children": [
{
"id": 13,
"name": "丽娜",
"gender": "女",
"age": 12,
"children": []
}
]
}
]
}
]
},
{
"id": 9,
"name": "范建强",
"gender": "男",
"age": 30,
"children": [
{
"id": 14,
"name": "文翰",
"gender": "男",
"age": 30,
"children": []
}
]
}
]