业务背景:el-table根据返回的数据动态渲染行和列
话不多说,上码,复制粘贴直接使用
关键点:
以如下代码为例:
1、动态渲染行列只需要一个 el-table-column 标签即可
2、必须有两个数组,分别代表列数组(colData)和行数组(rowData)
3、行下标:scope.$index; 列下标: index
一.每个单元格只有一项,不需要循环
效果:
完整代码:
<template>
<div class>
<el-table
:data="rowData"
border
style="width: 100%">
<el-table-column v-for="(item,index) in colData" :key="item.id" align="center">
<template slot="header">
<div>{{ item.label }}</div>
</template>
<template slot-scope="scope">
<span v-if="index == 0">
{{ scope.row.date }}
</span>
<span v-if="index > 0">
{{ scope.row[item.type] }}
</span>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
export default {
data () {
return {
colData: [
{
id: 1,
label: '日期/餐型'
},
{
id: 2,
label: '早餐',
type: 'BREAKFAST',
},
{
id: 3,
label: '午餐',
type: 'LUNCH',
},
{
id: 4,
label: '晚餐',
type: 'DINNER',
},
],
rowData: [{
date: '周一',
BREAKFAST: '苹果',
LUNCH: '白菜',
DINNER: "大米粥"
}, {
date: '周二',
BREAKFAST: '香蕉',
LUNCH: '土豆',
DINNER: "南瓜粥"
}, {
date: '周三',
BREAKFAST: '哈密瓜',
LUNCH: '西葫芦',
DINNER: "小米粥"
}],
}
},
}
</script>
二.每个单元格有多项,需要循环
效果:
完整代码:
<template>
<div class>
<el-table
:data="rowData"
border
header-cell-class-name="table-header"
style="width: 100%"
>
<el-table-column
v-for="(item, index) in colData"
:key="item.id"
align="center"
>
<template slot="header">
<div>{{ item.label }}</div>
</template>
<template slot-scope="scope">
<div v-if="index == 0">
{{ scope.row.date }}
</div>
<div v-if="index > 0">
<div v-for="ele in scope.row[item.type]" :key="ele.id">
{{ ele.name }}
</div>
</div>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
export default {
data() {
return {
colData: [
{
id: 1,
label: "日期/餐型",
},
{
id: 2,
label: "早餐",
type: "BREAKFAST",
},
{
id: 3,
label: "午餐",
type: "LUNCH",
},
{
id: 4,
label: "晚餐",
type: "DINNER",
},
],
rowData: [
{
date: "周一",
BREAKFAST: [
{
id: 1,
name: "杨梅",
},
{
id: 2,
name: "荔枝",
},
{
id: 3,
name: "凤梨",
},
],
LUNCH: [
{
id: 1,
name: "彩椒",
},
{
id: 2,
name: "韭菜",
},
],
DINNER: [
{
id: 1,
name: "大米粥",
},
],
},
{
date: "周二",
BREAKFAST: [
{
id: 1,
name: "百香果",
},
],
LUNCH: [
{
id: 1,
name: "胡萝卜",
},
{
id: 2,
name: "西兰花",
},
],
DINNER: [
{
id: 1,
name: "番茄鸡蛋粥",
},
{
id: 2,
name: "排骨芋头粥",
},
{
id: 3,
name: "窝蛋肉丝粥",
},
],
},
],
};
},
};
</script>
注意:数据结构需要自己处理成符合table规则的
如果对你有帮助,赏个三连呗🙇🙇,不胜感激Thanks♪(・ω・)ノ