vue使用递归组件实现多级列表

一、背景需求

在页面上渲染一个多级列表的时候,数据往往也具有多个层级
例如:数组的每个元素都是一个对象,对象中的value可能是一个数组

{
 "ret": true,
 "data": {
   "sightName": "大连圣亚海洋世界(AAAA景区)",
   "bannerImg": "",   
   "categoryList": [{
       "title": "成人票",
       "children": [{
         "title": "成人三馆联票",
         "children": [{
           "title": "成人三馆联票 - 某一连锁店销售"
         }]
       },{
         "title": "成人五馆联票"
       }]
     }, {
       "title": "学生票"
     }, {
       "title": "儿童票"
     }, {
       "title": "特惠票"
     }]
 }
}

在这种情况下,使用多重循环的HTML代码效率并不高,而且会增加后期维护的成本
vue提供了一种更好的实现方式:即递归组件

二、递归组件的概念和使用

递归组件,顾名思义,就是在组件内部调用自己
通过使用 组件的name选项 对应的标签,实现多重循环的效果
同时,在调用组件自身的时候,要通过v-if实现条件渲染
防止因无限调用组件而导致栈溢出

以上面给的数据为例,我们希望将 categoryList 渲染为多级列表
当父组件将 categoryList 传递给子组件的 list 变量后:

<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 v-if="item.children" class="item-children">
        <detail-list :list="item.children"></detail-list>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'DetailList',
  props: {
    list: Array
  }
}
</script>

若当前被循环的item有children,就递归调用自身,进入下一层级
实际的效果如下:
image.png

原文地址:https://www.cnblogs.com/baebae996/p/13361175.html