前言
哎,搞了一个多月,人都麻了......在导师的帮助下,从0到1开发了一个项目,果然是敏捷开发,一个人至少负责一个项目,每周五都要上线一次,忙疯。虽然天天被导师叼,奈何他远在深圳,诶我看不见,哈哈哈。不过还是被导师的能力所折服,我遇到问题就拉会找他,他接过便一边骂骂咧咧,一边三下五除二,‘duang’就出来了。牛逼plus。 最近碰到这样一个需求,要求前台做一个类似如下的表格:
咋一看,特简单,拿到数据一渲染就好了嘛,谁知表格后面的日期是动态生成的,而后台给我的数据是这样的:
tableData: [
{
periodId: '2016/10/02 14:42:30',
name: '王小虎',
gender: '男',
score1: 90,
score2: 94,
score3: 98
},
{
periodId: '2016/10/02 14:42:30',
name: '林小花',
gender: '女',
score1: 80,
score2: 90,
score3: 75
},
{
periodId: '2016/10/02 14:42:30',
name: '杨路',
gender: '女',
score1: 90,
score2: 99,
score3: 78
}]
于是厚着脸皮再次请教师父.....
第一步:封装格式化日期函数
虽然看不懂,咱会用就好了......
// 封装格式化日期
export const dateFormat = (fmt, date) => {
const o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds(),
'q+': Math.floor((date.getMonth() + 3) / 3),
'S': date.getMilliseconds()
}
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '')
.substr(4 - RegExp.$1.length))
}
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
fmt = fmt.replace(RegExp.$1, () => {
return (RegExp.$1.length == 1) ? o[k] : (`00${o[k]}`
.substr(('' + o[k]).length))
})
}
}
return fmt
}
第二步:处理动态表头
computed: {
dateCols(){
const [{ periodId = '' } = {}] = this.tableData
const t = new Date(periodId)
const y = t.getFullYear()
const m = t.getMonth()
const firstMonth = dateFormat('yyyy-MM',t)
const secondMonth = dateFormat('yyyy-MM',new Date(y,m+1))
const thirdMonth = dateFormat('yyyy-MM',new Date(y,m+2))
return [
{label: firstMonth, prop: 'score1'},
{label: secondMonth, prop: 'score2'},
{label: thirdMonth, prop: 'score3'}
]
}
}
第三步:el-table 渲染
<template>
<div class="text">
<h4>语文月考成绩表</h4>
<el-table :data="tableData" border style="width: 80%">
<el-table-column prop="name" label="姓名" width="100"></el-table-column>
<el-table-column prop="gender" label="性别" width="100"></el-table-column>
<el-table-column
v-for="(item,index) in dateCols"
:key="index"
:prop="item.prop"
:label="item.label"
>
</el-table-column>
</el-table>
</div>
</template>
大功告成啦,快去试试吧!