输出结果:
父组件:
<template>
<tree-item v-for="item in menuCustomData" :key="item.key" :item="item"></tree-item>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import TreeItem from './tree-item.vue';
export default defineComponent({
name: 'ButtonExample',
components: {
TreeItem,
},
setup() {
const menuCustomData = [
{
key: '1',
title: 'menu-1',
children: [
{
key: '1-1',
title: 'menu-1-1',
children: [
{
key: '1-1-1',
title: 'menu-1-1-1',
},
],
},
{
key: '1-2',
title: 'menu-1-2',
},
],
},
{
key: '2',
title: 'menu-2',
},
];
return {
menuCustomData,
};
},
});
</script>
子组件:
<template>
<h1>{{ item.title }} ---- {{ level }}</h1>
<template v-if="item && item.children">
<tree-item
v-for="v in item.children"
:key="v.key"
:level="innerLevel"
:item="v"
></tree-item>
</template>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
import type { PropType } from 'vue';
interface Item {
key: string;
title: string;
children?: Item[];
}
export default defineComponent({
name: 'TreeItem',
props: {
item: {
type: Object as PropType<Item>,
default: () => {},
},
level: {
type: Number,
default: 0,
},
},
setup(props) {
const innerLevel = ref<number>(1);
if (props.item.children && props.item.children.length > 0) {
innerLevel.value = props.level + 1;
}
return {
innerLevel,
};
},
});
</script>