实现成果
父组件调用:
<template> <div> <Tree :data="data"> <template #default="{ title }"> <div class="prent"> {{ title + "+自定义" }} </div> </template> </Tree> </div></template><script>import Tree from "./tree.vue";export default { components: { Tree, }, data() { return { data: [{ title: "父1", children: [{ title: "子", children:[{title:"孙",}] }], },{ title: "父2", children:[{title:"子"}] }] }; }};</script>
递归组件
<template> <div class="tree"> <div v-for="item of data" :key="item.title"> <!-- 显示title题目 --> <div class="title" > <!-- 插槽 --> <slot :title="item.title"> {{ item.title }} </slot> </div> <!-- 如果存在子项则调用自身组件 递归 --> <Tree v-if="item.children" :data='item.children' > <!-- 每个孩子的item 作用域插槽 --> <template v-slot="item"> <!-- 这里slot抛出给应用这个文件的作用域插槽 --> <slot :title='item.title' /> </template> </Tree> </div> </div></template><script>export default { name: 'Tree', props: { data: Array, }};</script><style scoped>.tree{ padding-left: 10px;}ul,li{ list-style: none; margin: 0; padding: 0;}</style>