由于业务需要,页面需要展示递归数据,原来的操作方法是自己去操作dom,但在Vue下可以使用组件自己调用自己的方式来处理递归数据
<!--父组件-->
<template>
<div class="home">
<ul>
<tree-item
v-for="item in TreeData"
:treeData="item"
:key="item.name"
></tree-item>
</ul>
</div>
</template>
<script>
import TreeItem from './path/to/TreeItem';
export default {
data() {
return {
TreeData: [
{
name: "node-1",
children: [
{
name: "node-1-1",
children: [
{
name: "node-1-1-1"
},
{
name: "node-1-1-2"
},
{
name: "node-1-1-3"
}
]
},
{
name: "node-1-2",
children: [
{
name: "node-1-2-1",
children: [
{
name: "node-1-2-1-1"
},
{
name: "node-1-2-1-2"
},
{
name: "node-1-2-1-3"
}
]
},
{
name: "node-1-2-2"
},
{
name: "node-1-2-3"
}
]
}
]
},
{
name: "node-2"
}
]
}
},
components: {
TreeItem
}
}
</script>
<!--子组件-->
<template>
<li class="tree-item">
<div class="name-text">{{ treeData.name }}</div>
<ul v-if="treeData.children && treeData.children.length" class="sub-items">
<tree-item
v-for="item in treeData.children"
:treeData="item"
:key="item.name"
></tree-item>
</ul>
</li>
</template>
<script>
export default {
name: "tree-item", // 递归的关键 !!!此处必须赋值才能自己调用自己
props: {
treeData: {
type: Object,
default() {
return {}
}
}
}
}
</script>
<style lang="less" scoped>
.tree-item {
.name-text {
text-align: left;
}
}
</style>
注意
子组件的name属性必须赋值,不然递归展示将会失效