递归组件使用
我们想要使用一个列表数据时需要通过v-for循环去循环列表,如果单层列表则循环一次即可,但是如果存在列表嵌套列表的情况,那么就需要多次v-for循环实现,这样就不符合我们的使用理念,此时使用递归组件则可以很好的实现上述情况
1、需要显示的地方进行第一次循环
2、在循环体内嵌套循环当前组件(这也就是为什么需要给组件定义name的原因之一,方便在递归时使用)
3、在当前组件上通过判断是否符合条件,然后将循环内容绑定即可
以项目为例
①在Detail.vue定义列表
<template>
<div>
<detail-banner></detail-banner>
<detail-header></detail-header>
<div class="content">
<detail-list :list="list"></detail-list>
</div>
</div>
</template>
<script>
import DetailBanner from './components/Banner'
import DetailHeader from './components/Header'
import DetailList from './components/List'
export default {
name: 'Detail',
components: {
DetailBanner,
DetailHeader,
DetailList
},
data () {
return {
// 定义多层列表
list: [{
title: '成人票',
children: [{
title: '成人三馆联票',
children: [{
title: '成人三馆联票 - 某一连锁店销售'
}]
}, {
title: '成人三馆联票'
}]
}, {
title: '学生票'
}, {
title: '儿童票'
}, {
title: '特惠票'
}]
}
}
}
</script>
<style lang="stylus" scoped>
.content
height 50rem
</style>
②在列表中显示
<template>
<div>
// 第一层循环
<div class="item" v-for="(item, index) of list" :key="index">
<div class="item-title border-bottom">
<span class="item-title-icon"></span>
{{item.title}}
</div>
// 循环组件
<div class="item-children" v-if="item.children">
// 绑定递归循环内容
<detail-list :list="item.children"></detail-list>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'DetailList',
props: {
list: Array
}
}
</script>
<style lang="stylus" scoped>
@import '~styles/varibles.styl'
.border-bottom
&:before
border-color #ccc
.item
.item-title
line-height .8rem
font-size .32rem
padding 0 .2rem
.item-title-icon
position relative
left .06rem
top .06rem
display: inline-block;
width: .36rem;
height: .36rem;
background: url(http://s.qunarzz.com/piao/image/touch/sight/detail.png) 0 -.45rem no-repeat;
margin-right: .1rem;
background-size: .4rem 3rem;
.item-children
padding 0 .2rem
</style>