递归组件
什么是递归组件?
组件自身去调用组件自身。
代码示例
DetailList.vue(子组件-递归组件)
<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> <!--递归组件:DetailList调用自身--> <div v-if="item.children" class="item-children"> <detail-list :list="item.children"></detail-list> </div> </div> </div> </template>
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.vue' import DetailHeader from './components/Header.vue' import DetailList from './components/List.vue' export default{ name: 'Detail', components: { DetailBanner, DetailHeader, DetailList }, data(){ return { list: [{ title: '成人票', children: [{ title: '成人3馆联票', children: [{title: '成人3馆联票-成都'}, {title: '成人3馆联票-上海'}, {title: '成人3馆联票-北京'}, {title: '成人3馆联票-河南'}] }, { title: '成人4馆联票' }, { title: '成人5馆联票' }, { title: '成人6馆联票' }] }, { title: '学生票' }, { title: '儿童票' }, { title: '特惠票' }] } } } </script>
注意:父组件中的数据结构是二维数组。子组件调用自身之后,对于css样式,我们只要仅仅关注一级列表即可,二级列表会自动使用相同的样式。如图: