递归组件应用在于 不确定有多少子集 而渲染需要调用自身模版不断渲染,最终达成所需的dom格式
由两个vue页面来演示递归组件#####
1.数据传入页 Mode
<template>
<div>
<my-trees :list="list"></my-trees>
</div>
</template>
<script>
import myTrees from './treeMenus'
export default {
data(){
return {
list: [
{
name: '黄焖鸡米饭111111111',
cList: [
{ name: '二级黄焖鸡' },
{
name: 'one chicken',
cList: [
{ name: '三级黄焖鸡3333', cList: [{ name: '四级黄焖鸡' }] }
]
}
]
},
{
name: '2222222222',
cList: [
{ name: '二级黄焖鸡' },
{
name: 'one chicken',
cList: [
{ name: '三级黄焖鸡3333', cList: [{ name: '四级黄焖鸡' }] }
]
}
]
},
{
name: '黄焖鸡米饭33333333',
cList: [
{ name: '二级黄焖鸡' },
{ name: 'one chicken' }
]
}
]
}
},
components: {
myTrees
}
}
</script>
2.递归组件 treeMenus.vue
<template>
<ul>
<li v-for="(item,index) in list" :key="index">
<p @click="changeStatus(index)">{{item.name}}</p>
<!-- 递归组件 每次往下传入下一级的数据 scopesDefault[index]控制显隐-->
<tree-menus v-if="scopesDefault[index]" :list="item.cList"></tree-menus>
</li>
</ul>
</template>
<script>
export default {
name: 'treeMenus',
props: {
list: Array
},
data() {
return {
scopesDefault: [],
scopes: []
}
},
methods: {
changeStatus(index) {
if (this.scopesDefault[index] == true) {//控制下级显隐
this.$set(this.scopesDefault, index, false)
} else {
this.$set(this.scopesDefault, index, this.scopes[index])
}
},
scope() {//遍历数据
this.list.forEach((item, index) => {//循环数据
this.scopesDefault[index] = false
if ('cList' in item) {//当前还有下级
this.scopes[index] = true
} else {//当前没有下级
this.scopes[index] = false
}
})
}
},
created() {
this.scope()//初始化显示内容
}
}
</script>
<style>
ul {
margin-top: 50px;
padding-left: 20px !important;
}
</style>