如图所示,可以实现树状数据的新增子项,新增平级,删除。主要用到了递归
代码:
<template>
<el-table :data="tableData" style="width: 100%; margin-bottom: 20px" row-key="id" border default-expand-all>
<el-table-column prop="date" label="Date" />
<el-table-column prop="name" label="Name" />
<el-table-column prop="address" label="Address" />
<el-table-column label="Operations">
<template #default="scope">
<el-button size="small" @click="add(scope.row)">新增平级</el-button>
<el-button size="small" @click="addSon(scope.row)">新增子级</el-button>
<el-button size="small" type="danger" @click="delItem(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
const tableData = ref([
{
id: 1,
date: '2016-05-02',
name: 'wangxiaohu',
address: 'No. 189, Grove St, Los Angeles',
},
{
id: 2,
date: '2016-05-04',
name: 'wangxiaohu',
address: 'No. 189, Grove St, Los Angeles',
},
{
id: 3,
date: '2016-05-01',
name: 'wangxiaohu',
address: 'No. 189, Grove St, Los Angeles',
children: [
{
id: 31,
date: '2016-05-01',
name: 'wangxiaohu',
address: 'No. 189, Grove St, Los Angeles',
},
{
id: 32,
date: '2016-05-01',
name: 'wangxiaohu',
address: 'No. 189, Grove St, Los Angeles',
},
],
},
{
id: 4,
date: '2016-05-03',
name: 'wangxiaohu',
address: 'No. 189, Grove St, Los Angeles',
},
])
// 平级新增递归的方法
const addLeaveLoop = (arr: any[], id: number | string) => {
for (let i = 0; i < arr.length; i++) {
if (arr[i].id === id) {
arr.splice(i + 1, 0, { id: +new Date(), date: '2023-11-03', name: '辉辉', address: 'dashjdsakljdl' })
} else if (arr[i].children) {
arr[i].children = addLeaveLoop(arr[i].children, id)
}
}
return arr
}
// 新增平级
const add = (row: any) => {
addLeaveLoop(tableData.value, row.id)
}
// 新增一个子节点的方法
const addSonLoop = (arr: any[], id: number | string) => {
for (let i = 0; i < arr.length; i++) {
if (arr[i].id === id) {
// 判断有没有children,有就前面新增,没有就创建
if (arr[i].children && arr[i].children.length) {
arr[i].children.unshift({ id: +new Date(), date: '2023-11-03', name: '张三', address: 'dashjdsakljdl' })
} else {
arr[i].children = [{ id: +new Date(), date: '2023-11-03', name: '李四', address: 'dashjdsakljdl' }]
}
} else if (arr[i].children) {
arr[i].children = addSonLoop(arr[i].children, id)
}
}
return arr
}
// 新增子级
const addSon = (row: any) => {
addSonLoop(tableData.value, row.id)
}
// 删除递归的方法
const delLoop = (arr: any[], id: number | string) => {
for (let i = 0; i < arr.length; i++) {
if (arr[i].id === id) {
arr.splice(i, 1)
} else if (arr[i].children) {
arr[i].children = delLoop(arr[i].children, id)
}
}
return arr
}
// 删除
const delItem = (row: any) => {
delLoop(tableData.value, row.id)
}
</script>