1.数据在父组件中:父组件传值+子组件自调用
父:
<template>
<div class="hello">
<comp1 :treeList="tryData"></comp1>//给子组件传值
</div>
</template>
<script>
import comp1 from './comp1/index.vue'
export default {
name: 'HelloWorld',
components:{comp1},
data () {
return {
tryData: [
{ id: 0, show: true, children: [{ id: 1 }, { id: 4 }] },
{ id: 2, show: false, children: [{ id: 5 }] },
{
id: 3,
show: true,
children: [
{ id: 6 },
{ id: 7 },
{ id: 8, show: false, children: [{ id: 9 }, { id: 10 }] },
],
},
],
}
}
}
</script>
子:
<template>
<div>
<ul v-if="treeList">
<li v-for="it in treeList" :key="it.id">//展示一层结构
{{ it.id }}
//在li里通过自调用展示多层结构
<comp1 v-if="it.children" :treeList="it.children"></comp1>
</li>
</ul>
</div>
</template>
<script>
export default {
name: "comp1",
props:['treeList']//别忘了加引号
};
</script>
2.数据在子组件里:递归创建节点字符串,v-html将其插入到template中
<template>
<div v-html="str"></div>
</template>
<script>
export default {
name: "comp1",
data() {
return {
tryData: [
{ id: 0, show: true, children: [{ id: 1 }, { id: 4 }] },
{ id: 2, show: false, children: [{ id: 5 }] },
{
id: 3,
show: true,
children: [
{ id: 6 },
{ id: 7 },
{ id: 8, show: false, children: [{ id: 9 }, { id: 10 }] },
],
},
],
str: "",
};
},
methods: {
build(arr) {
if (arr.length == 0) return;
this.str = this.str.concat(`<ul>`);
console.log(arr[0])
for (let i=0;i<arr.length;i++) {
console.log(i)
this.str = this.str.concat(`<li>`);
this.str = this.str.concat(`${arr[i].id}`);
if (arr[i].children) this.build(arr[i].children);
this.str = this.str.concat(`</li>`);
}
this.str = this.str.concat(`</ul>`);
},
},
mounted() {
this.build(this.tryData);
},
};
</script>
结果展示: