效果
想要的效果:因为1~12月的数据是动态获取的,而且格式相同,通过循环月份数据简化代码,下面是要实现的效果:
实现
HTML代码
<div v-for="(item, index) in months" :key="index">
<el-table-column :label="curYear + '年' + item + '月'">
<el-table-column label="实际销售" label-class-name="c2">
<el-table-column :label="`${curYear}`" label-class-name="c2">
<template slot-scope="scope">
{{ daily(scope.row.monthData[index].data,'sellReal',curYear) }}
</template>
</el-table-column>
<el-table-column :label="`${curYear-1}`" label-class-name="c2">
<template slot-scope="scope">
{{ daily(scope.row.monthData[index].data,'sellReal',curYear-1) }}
</template>
</el-table-column>
<el-table-column :label="`${curYear-2}`" label-class-name="c2">
<template slot-scope="scope">
{{ daily(scope.row.monthData[index].data,'sellReal',curYear-2) }}
</template>
</el-table-column>
</el-table-column>
<el-table-column label="同比" label-class-name="c2">
<el-table-column :label="`${curShortYear}&${curShortYear-1}`" prop="ratio_last" label-class-name="c2">
<template slot-scope="scope">
<span :style="{color: colorColoum(scope.row.monthData[index].ratio_last, true)}">{{ scope.row.monthData[index].ratio_last }}</span>
</template>
</el-table-column>
<el-table-column :label="`${curShortYear}&${curShortYear-2}`" prop="ratio_prev" label-class-name="c2">
<template slot-scope="scope">
<span :style="{color: colorColoum(scope.row.monthData[index].ratio_prev, true)}">{{ scope.row.monthData[index].ratio_prev }}</span>
</template>
</el-table-column>
</el-table-column>
<el-table-column label="控比" label-class-name="c2">
<el-table-column label="****" prop="ratio_cb" label-class-name="c2">
<template slot-scope="scope">
<span :style="{color: colorColoum(scope.row.monthData[index].ratio_cb, false)}">{{ scope.row.monthData[index].ratio_cb }}</span>
</template>
</el-table-column>
</el-table-column>
</el-table-column>
</div>
JS代码:
data() {
return {
tableData: [], // el-table 绑定的data数据
// tableData的数据格式:
//tableData: [
// {
// rowName: '第一列数据的名称,如店铺名称之类的',
// monthData: [{month: '01', ...}, {month: '02', ...}, ...], // 你的月份数据,对应months数组
// }
//]
months: ['01'], // 这里只默认了1月,具体的看你的数据有几个月,在处理数据时动态赋值
curYear: null // 当前年份,自己在数据处理时动态赋值
}
}
//再补充一个通过条件给单元格标颜色的方法,与嵌套循环配套使用(普通的表格可以用cell-style更简单)
methods: {
// 其实js很简单,一个方法就搞定了,重点是上面的html代码,注意我们要绑定样式,必须在template标签里再嵌套一个span标签哦
colorColoum(param, isMinus) {
if (isMinus) {
if (param.split('%')[0] < 0) {
return 'red'
}
} else {
if (param.split('%')[0] < 100) {
return 'red'
}
}
return 'black'
},
}