日常開發中常常要是用表格展示一些數據,在我們展示這些數據時,有時需要對數據進行預處理,大多包含時間、布爾值等,偶爾在網上看到一個數據處理(或者叫數據個時候吧)的方法,記錄一下吧。
<el-table-column label="時間" :formatter="formatDate" width="300" />
- 使用formatter來代替原來的prop,綁定table單行的值。
- formatter有三個形參,第一個row就是綁定formatter這一行的所有的數據。用它來格式化數據。
formatDate(row, column, cellValue) {
const startTime = new Date(row.start_time)
const endTime = new Date(row.end_time)
if (startTime.getDay() === endTime.getDay()) {
let hour = endTime.getHours()
if (hour <= 9) { hour = '0' + hour }
let min = endTime.getMinutes()
if (min <= 9) { min = '0' + min }
let sec = endTime.getSeconds()
if (sec <= 9) { sec = '0' + sec }
return row.start_time + ' - ' + hour + ':' + min + ':' + sec
} else {
let mouth = endTime.getMonth() + 1
if (mouth <= 9) { mouth = '0' + mouth }
let day = endTime.getDay()
if (day <= 9) { day = '0' + day }
let hour = endTime.getHours()
if (hour <= 9) { hour = '0' + hour }
let min = endTime.getMinutes()
if (min <= 9) { min = '0' + min }
let sec = endTime.getSeconds()
if (sec <= 9) { sec = '0' + sec }
return row.start_time + ' - ' + mouth + '-' + day + ' ' + hour + ':' + min + ':' + sec
}