常使用elementUI的el-table时,其绑定的数据是一个数组,如果这个数组中有一个对象,直接去渲染则无法实现
我可以参考以下代码示例来实现el-table对象数组中嵌套的对象数组的渲染: 数据结构:
[
{
id: 1,
name: 'Tom',
details: [
{ age: 20, gender: 'Male' },
{ age: 21, gender: 'Female' }
]
},
{
id: 2,
name: 'Jerry',
details: [
{ age: 22, gender: 'Male' },
{ age: 23, gender: 'Female' }
]
}
]
模板代码:
<el-table :data="tableData" style="width: 100%">
<el-table-column prop="id" label="ID"></el-table-column>
<el-table-column prop="name" label="Name"></el-table-column>
<el-table-column label="Details">
<template slot-scope="scope">
<el-table :data="scope.row.details" style="width: 100%">
<el-table-column prop="age" label="Age"></el-table-column>
<el-table-column prop="gender" label="Gender"></el-table-column>
</el-table>
</template>
</el-table-column>
</el-table>
在el-table-column中使用template来嵌套一个子el-table,通过scope.row.details可以获取到当前行的details数据,实现数据的嵌套展示。在子el-table中的el-table-column中设置prop来指定表格列展示的数据。
在 el-table 中使用 el-table-column 组件来渲染对象数组的每一列数据。
对于需要渲染嵌套对象数组的列,使用 scoped slot 来自定义渲染方式。
在 scoped slot 中使用 el-table 组件来渲染嵌套对象数组的每一行数据。
<template>
<el-table :data="tableData">
<el-table-column prop="name" label="Name"></el-table-column>
<el-table-column label="Nested Object">
<template slot-scope="scope">
<el-table :data="scope.row.nestedArray">
<el-table-column prop="prop1" label="Prop1"></el-table-column>
<el-table-column prop="prop2" label="Prop2"></el-table-column>
</el-table>
</template>
</el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{
name: 'Object 1',
nestedArray: [
{ prop1: 'Value 1', prop2: 'Value 2' },
{ prop1: 'Value 3', prop2: 'Value 4' }
]
},
{
name: 'Object 2',
nestedArray: [
{ prop1: 'Value 5', prop2: 'Value 6' },
{ prop1: 'Value 7', prop2: 'Value 8' }
]
}
]
};
}
};
</script>
在上面的示例代码中,使用了 el-table-column 的 scoped slot 来渲染嵌套对象数组的列,使用了 el-table 组件来渲染嵌套对象数组的每一行数据。
希望可以帮助到您,望采纳!