本文参考孙卫琴,杜聚宾所创作的 <<精通Vue.js: Web前端开发技术详解>>一书
在一个组件的模板中,还可以嵌套自身组件,这样就构成了组件的递归。为了避免无限递归,需要设置递归的结束条件。在例程1的recursive.html中,组件的模板会插入自身组件,从而递归遍历访问list数组中的所有嵌套的元素。模板中“”的v-if指令用来设置递归结束条件,当list数组为空,就结束递归。
例程1 recursive.html
<div id="app">
<category :list="items"></category>
</div>
<script>
const app=Vue.createApp({
data(){
return {
items:[{
type:'生物',
subtype:[
{
type:'植物',
subtype:[{type:'树木'},{type:'灌木'},{type:'青草'}]
},
{
type:'动物',
subtype:[{type:'猫'},
{type:'狗'},
{type:'鱼',
subtype:[{type:'鲤鱼'},{type:'鲨鱼'}]}
]
}
]
}]
}
}
})
app.component('category', {
props:{
list:{type:Array}
},
template: ` <ul><template v-if="list">
<li v-for="item in list">
{{item.type}}
<category :list="item.subtype"></category>
</li>
</template></ul> `
})
app.mount('#app')
</script>
通过浏览器访问recursive.html,会得到如图1所示的网页,list数组中的嵌套内容会以缩进对齐的方式一层层展示出来。
图1 recursive.html的网页