<templat>
<div>
<el-button @click="addRow">Add Row</el-button>
<el-button @click="deleteAllRows">Delete All Rows</el-button>
<el-table
:data="tableData"
style="width: 100%"
row-key="id"
border
lazy
:load="load"
:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
height="500px"
>
<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="Actions">
<template #default="{ row }">
<el-button @click="addChild(row)">Add Child</el-button>
<el-button @click="deleteRow(row)">Delete Row</el-button>
</template>
</el-table-column>
<el-table-column type="expand">
<template #default="{ row }">
<el-table v-if="row.children && row.children.length > 0" :data="row.children" style="width: 100%">
<el-table-column prop="date" label="DateChild" />
<el-table-column prop="name" label="NameChild" />
<el-table-column prop="address" label="AddressChild" />
<!-- 继续添加子级数据的表头 -->
<el-table-column label="Actions">
<template #default="{ row, $index }">
<el-button @click="deleteChild(row)">Delete Child</el-button>
</template>
</el-table-column>
</el-table>
</template>
</el-table-column>
</el-table>
</div>
</template>
// 初始数据
const tableData = ref([
{
id: 1,
date: '2022-01-01',
name: 'John',
address: 'New York',
children: [
{
id: 11,
date: '2022-01-02',
name: 'May',
address: 'Los Angeles'
}
]
},
{
id: 2,
date: '2022-01-02',
name: 'Jane',
address: 'San Francisco'
}
]);
// 添加行
const addRow = () => {
const newRow = {
id: Date.now(),
date: '',
name: '',
address: '',
children: []
};
tableData.value.push(newRow);
};
// 删除行
const deleteRow = (row) => {
const index = tableData.value.indexOf(row);
if (index !== -1) {
tableData.value.splice(index, 1);
}
};
// 添加子行
const addChild = (row) => {
if (!row.children) {
row.children = [];
}
row.children.push({
id: Date.now(),
date: '',
name: '',
address: ''
});
};
// 删除子行
const deleteChild = (childRow) => {
// 通过 childRow 访问父级行数据
const parentRow = getParentRow(childRow);
if (parentRow) {
const childIndex = parentRow.children.indexOf(childRow);
if (childIndex !== -1) {
parentRow.children.splice(childIndex, 1);
} else {
console.warn('Child not found');
}
}
};
// 辅助函数,用于获取父级行数据
const getParentRow = (childRow) => {
for (const row of tableData.value) {
if (row.children && row.children.includes(childRow)) {
return row;
}
}
return null;
};
// 删除所有行
const deleteAllRows = () => {
tableData.value = [];
};