第七章 递归组件(树组件为例)

递归组件

封装树组件

App.vue

<template>
  <div class="App">
    App
    <MyTree :dataList="dataList"></MyTree>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import MyTree from "./components/GolbalComponents/MyTree.vue";

// 定义树的接口
interface ITree {
  name: string;
  checked: boolean;
  children?: ITree[] | []
}

// 数据
const dataList = reactive<ITree[]>([
  {
    name:'1',
    checked: false,
  },
  {
    name:'2',
    checked: true,
    children: [
      {
        name:'2-1',
        checked: false,
      }
    ]
  }, 
  {
    name:'3',
    checked: false,
    children: [
      {
        name:'3-1',
        checked: false,
      },
      {
        name:'3-2',
        checked: false,
      }
    ]
  },
])

</script>

MyTree.vue

<template>
  <div class="Tree">
    <div class="container" v-for="item in dataList" :key="item.name">
      
      <input type="checkbox" v-model="item.checked"> <span>{{ item.name }}</span> 
      <!-- 
        递归:递归出口v-if="item?.children?.length"
      -->
      <MyTree v-if="item?.children?.length" :dataList="item.children"></MyTree>
    </div>
  </div>
</template>

<script setup lang="ts">
// 定义树的接口
interface ITree {
  name: string;
  checked: boolean;
  children?: ITree[] | []
}

// ts写法
const props = defineProps<{
  dataList: ITree[]
}>();
console.log(props.dataList);

// ts默认值
// const props = withDefaults(
//   defineProps<{
//     dataList: ITree[]
//   }>(),
//   {

//   }
// )

// js写法
// const props = defineProps(['dataList']);

// js默认值
// const props = defineProps({
//   dataList: {
//     type: Array,
//     default: ()=>([])
//   }
// });
</script>

<style scoped>
.container{
  margin-left: 10px;
}
</style>

在这里插入图片描述

自定义递归组件名

在这里插入图片描述

转换列表数据为树状结构

数据格式

  • pid 父级id
  • id 当前数据id
{id: "604e223fb205b95968e1312b", pid: "", name: "人事部", code: "RSB", manager: "战三", introduce: "人事部",}
{id: "604e2251b205b95968e1312c", pid: "604e223fb205b95968e1312b", name: "财务部", code: "CWB1", manager: "管理员", introduce: "财务部",}

处理到二级目录

transListToTreeData(list, searchVal) {
  // 1.找到pid为searchVal的所有父级
  const arr = []
  list.forEach(item => {
    if (item.pid === searchVal) {
      arr.push(item)
    }
  })

  // 2.比较父级id和所有数据的pid,为父级添加对应的子级
  arr.forEach(item => {
    const children = list.filter(obj => obj.pid === item.id) || []
    item.children = children
  })

  return arr
},

递归处理

transListToTreeData2(list, searchVal) {
  // 1.找到pid为searchVal的所有父级
  const arr = []
  list.forEach(item => {
    if (item.pid === searchVal) {
      // 2.比较父级id和所有数据的pid,为父级添加对应的子级
      const children = this.transListToTreeData2(list, item.id) || []
      item.children = children
      arr.push(item)
    }
  })

  return arr
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值