递归组件
封装树组件
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
}