js里面有遞歸算法,同時,我們也可以利用props來實現vue模板的遞歸調用,但是前提是組件擁有 name 屬性
父組件:slotDemo.vue:
<template>
<div>
<!-----遞歸組件----->
<ul>
<simple3 :tree="item" v-for="item in tree"></simple3>
</ul>
</div>
</template>
<style lang="stylus" rel="stylesheet/stylus">
li
padding-left 30px
</style>
<script>
import simple3 from "./simple/simple3.vue";
export default{
data(){
return {
tree: [{
label: "一級菜單",
test:1,
children: [{
label: "二級菜單",
test:2,
children: [{
label: "三級菜單",
test:3
}]
}]
}]
}
},
components: {
simple3
}
}
</script>
子組件:simple3.vue
<template>
<li>
<a>{{tree.label}}</a>
<simple3 v-if="tree.children" :tree="item" v-for="item in tree.children" :class="item.test==2?'test2':'test3'"></simple3>
</li>
</template>
<style rel="stylesheet/stylus" lang="stylus">
.test2
list-style disc
.test3
list-style decimal
</style>
<script>
export default{
name: "simple3",
props: ["tree"]
}
</script>
上面是一個子組件,定義了 name 為 simple03,然后在模板中調用自身,結合 v-for 實現遞歸
為了防止出現死循環,在調用自身的時候,加入了 v-if 作為判定條件
父組件中調用的時候,需要通過 props 傳入一個 tree;
為了對每一級菜單有所區分,我對tree里面的每一個子集合里面加了一個test字段來區分是哪一級的菜單然后對其不同的樣式進行處理
最后的效果:

