1、呈现效果:
2、代码实现
2-1、src/App.vue 代码:
<template>
<div>
<h3>递归组件示例</h3>
<ChildItem
v-for="(item, index) in list"
:key="item.id"
:item="item"
>
</ChildItem>
</div>
</template>
<script setup>
import { ref } from "vue";
import ChildItem from '@/views/childItem/index.vue'
const list = ref([
{
id: 1001,
content: '销售部',
children: [
{
id: 100101,
content: '小刘',
},
{
id: 100102,
content: '小章',
},
]
},
{
id: 1002,
content: '财务部',
children: [
{
id: 100101,
content: '小李',
},
{
id: 100102,
content: '小王',
children: [
{
id: 100101,
content: '小关',
},
{
id: 100101,
content: '小何',
},
{
id: 100101,
content: '小谢',
},
{
id: 100101,
content: '小吴',
}
]
},
{
id: 100102,
content: '小赵',
},
]
},
{
id: 1003,
content: '行政部'
}
])
</script>
<style lang="scss" scoped></style>
2-2、src/views/childItem/index.vue 代码:
<template>
<div>
<h5>{{ item.id }} --- {{ item.content }}</h5>
<ChildItem
v-for="(child, index) in item.children"
:key="index" :item="child"
style="margin-left: 20px;">
</ChildItem>
</div>
</template>
<script lang="ts">
export default {
name: 'ChildItem'
}
</script>
<script setup lang="ts">
const props = defineProps(['item'])
console.log(props);
</script>
<style lang="scss" scoped></style>
简单的组件递归效果实现!快去试试吧~