在做一个项目中碰到的问题,就是当你要传入el-table的数据是一个类似如下的嵌套二级列表:
[
{
"id": 1,
"username": "root",
"score": 0,
"penalty": 240,
"problemScore": [
{ "id": 1, "accepted": false, "error": 0, "timeUsage": 0},
{ "id": 2, "accepted": true, "error": 0, "timeUsage": 120},
{ "id": 3, "accepted": true, "error": 0, "timeUsage": 240}
]
},
{
"id": 2,
"username": "tets",
"score": 0,
"penalty": 640,
"problemScore": [
{ "id": 1, "accepted": true, "error": 0, "timeUsage": 20 },
{ "id": 2, "accepted": true, "error": 0, "timeUsage": 300},
{ "id": 3, "accepted": true, "error": 0, "timeUsage": 640}
]
},
{
"id": 3,
"username": "test2",
"score": 0,
"penalty":300,
"problemScore": [
{ "id": 1, "accepted": false, "error": 0, "timeUsage": 0},
{ "id": 2, "accepted": false, "error": 0, "timeUsage": 0},
{ "id": 3, "accepted": false, "error": 0, "timeUsage": 0}
]
}
]
并且要达到这样的效果:
![](https://img.haomeiwen.com/i12775720/941a374b624c7f54.png)
需要解决的困难为:
- 如何在el-table中传入第二级列表元素,并且在能够把这些元素追加在一级列表的列后面?
直接上代码,我的处理方法是:
二级列表的长度用problemScore.lenght
是读取不到的,因为这个table内属性在vue的层面上是读取不到的,prop接收的只是一个字符串(注意它没有用:prop而是prop),所以要用v-for
还是得事先用this.problemSize = this.rankData[0].problemScore.length
把二级列表的长度提取出来让v-for
能够正常进行。
接着就是最重要的一句::prop="`problemScore[${index-1}].displayText`"
因为我们知道prop接收的只是一个字符串,所以我们用可以es6的模板字符串来把这个字符串对象传给prop,这样就能满足我们的需求。
<el-table
:data="rankData"
style="width: 100%"
:cell-style="cellStyle"
border
>
<el-table-column
label="#"
type="index"
/>
<el-table-column
label="用户名"
prop="username"
width="120"
/>
<el-table-column
label="总分数"
prop="score"
width="80"
/>
<el-table-column
label="总用时"
prop="displayPenalty"
width="100"
/>
<el-table-column
v-for="index in problemSize"
:key="index"
:prop="`problemScore[${index-1}].displayText`"
:label="index.toString()"
/>
</el-table>
- 关于单元格颜色。
这里我事先在数据请求完后用forEach对需要红色的单元格带上了colorType=2,需要绿色的单元格带上了colorType=1,然后用了:cell-style="cellStyle"
来给el-table绑定颜色渲染方法。
因为table的每一行rowIndex和数据的每一行对应,列columnIndex-4对应着数据的第二级列表的每一项,因此cellStyle方法写成了下面这样:
cellStyle ({ row, column, rowIndex, columnIndex }) {
if (columnIndex >= 4 && this.rankData[rowIndex].problemScore[columnIndex - 4].colorType === 1) {
return 'background:#67C23A;color:white;'
} else if (columnIndex >= 4 && this.rankData[rowIndex].problemScore[columnIndex - 4].colorType === 2) {
return 'background:#F56C6C;color:white;'
} else {
return ''
}
},
网友评论