vue+Element-ui的el-table的多级内容渲染问题
作者:鸣拙
这篇文章主要介绍了vue+Element-ui的el-table的多级内容渲染问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
vue+Element-ui的el-table的多级内容渲染
将多层内容渲染到表格里面
平常的表格是一个对象里面的数据渲染成一行,对象里面的key就是表格的label,如果对象里面还有对象数组那该怎么去渲染,如渲染下面的数据,将一个对象渲染成一行数据,和平常的table表格的数据渲染不一样,这个不能直接渲染出来,需要加第三方的label来渲染数据
tableData: [
{
name: 'Huawei P40',
properties: [
{
description: '颜色',
value: '红色'
},
{
description: '内存',
value: '128G'
}
]
},
{
name: '小米10',
properties: [
{
description: '颜色',
value: '黑色'
},
{
description: '内存',
value: '128G'
}
]
}
]
代码如下,另外加一个columnIndex数组,用来存储数据里面的属性的key
<template>
<el-table :data="tableData" border>
<el-table-column label="手机">
<template slot-scope="scope">
<span>{{scope.row.name}}</span>
</template>
</el-table-column>
<el-table-column v-for="(item, index) in columnIndex" :key="index" :label="item">
<template slot-scope="scope">
<span>{{scope.row.properties[index].value}}</span>
</template>
</el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
// 有两层数据,渲染表格
columnIndex: ['颜色','内存'],
tableData: [
{
name: 'Huawei P40',
properties: [
{
description: '颜色',
value: '红色'
},
{
description: '内存',
value: '128G'
}
]
},
{
name: '小米10',
properties: [
{
description: '颜色',
value: '黑色'
},
{
description: '内存',
value: '128G'
}
]
}
]
}
}
}
</script>
<style>
</style>
效果图:
可以看到,properties里面的数据也渲染到表格里面了

Element UI 多级表格渲染
// TableColumn.js
function renderColumn(h, column){
return h{
'el-table-column',
{
props:{
align:'center',
...column
}
},
column&&column.children&&column.children.map(c=> renderColumn(h, c))
}
}
export default {
functional: true,
props: {
columns: {
type:Array,
default: ()=>[]
}
},
render(h, ctx) {
return ctx.props.columns.map(column => renderColumn(h, column ))
}
}// Table.vue
<template>
<el-table
ref="elTable"
:data="list"
stripe
border
height="100%"
>
</el-table>
</template>
<script>
import TableColumn from './TableColumn.js'
const columns = [
{
label:'一级',
children:[
{
label:'二级一',
align:'center',
prop:'name1'
},
{
label:'二级二',
children:[
{
label:'三级一',
align:'center',
prop:'name2'
},
{
label:'三级二',
align:'center',
prop:'name3'
}
]
}
]
}
]
export default {
name: "Table",
data() {
return {
list:[]
}
}
}
</script>总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
