在開發(fā)中遇到了這樣一個問題,就是接好接口以后數(shù)據(jù)庫中傳入的值為'true'和'false'這樣的布爾值或者是'0' , '1' , '2'這樣數(shù)字,還有一種是傳入的是時間戳也就是類似'1575949565559'這樣子,而實際上他們是有相對應(yīng)的中文值的,這里提供一種轉(zhuǎn)換的思路。
- 布爾類型轉(zhuǎn)換
- 數(shù)字類型轉(zhuǎn)換
- 時間戳轉(zhuǎn)換
1、布爾類型轉(zhuǎn)換
一般來說像這種返回結(jié)果,在數(shù)據(jù)庫中存儲的值都是布爾類型的。例:

而我想要的效果是

其實很簡單,在el-table-column中加入一個<template slot-scope="scope"></template>就可以實現(xiàn)。這應(yīng)該是文檔中關(guān)于插槽的內(nèi)容。
我實現(xiàn)的代碼:注意prop值要相對應(yīng)
<el-table-column label="登錄結(jié)果" prop="result" align="center" width="130px">
<template slot-scope="scope">{{ !!(scope.row.result)?'成功':'不成功' }}</template>
</el-table-column>
2、數(shù)字類型
同樣我又遇到了另外一個問題,就是當(dāng)傳過來的值是數(shù)字類型的話怎樣用三元運(yùn)算符來解決呢??梢钥吹浇涌谥袀魅氲氖菙?shù)字。

實際上我想要的是

實現(xiàn)代碼有兩種:
一是類似布爾類型,在三元運(yùn)算符中加入判斷,以及嵌套實現(xiàn)。
<el-table-column label="類型" prop="type" align="center" width="80px">
<template slot-scope="scope">
{{ scope.row.type == 1 ? '表單' : scope.row.type == 2 ?'列表': '' }}
</template>
</el-table-column>
第二種方法:
<el-table-column label="類型" prop="type" align="center" width="80px">
<template slot-scope="scope">
{{ map[scope.row.type] }}
</template>
</el-table-column>
在data中定義一個map存儲根據(jù)map的值來對應(yīng)轉(zhuǎn)換的數(shù)據(jù)
data() {
return {
map: {
1: '表單',
2: '列表',
3: '列表和打印'
}
}
},
3、時間戳轉(zhuǎn)換
我又遇到了一個從數(shù)據(jù)庫中導(dǎo)入時間后,顯示的是這樣的= =什么鬼,查了一下原來是時間戳。這里一起寫了解決方法。

HTML中的代碼:利用element-UI 的 formatter 進(jìn)行轉(zhuǎn)換
<el-table-column label="創(chuàng)建時間" prop="createTime" :formatter="timestampToTime" align="center" width="140" />
在methods中寫一個 timestampToTime 這樣的方法
// 時間戳轉(zhuǎn)化為時間
timestampToTime(row, column) {
var date = new Date(row.createTime) // 時間戳為10位需*1000,時間戳為13位的話不需乘1000
var Y = date.getFullYear() + '-'
var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
var D = date.getDate() + ' '
var h = date.getHours() + ':'
var m = date.getMinutes() + ':'
var s = date.getSeconds()
return Y + M + D + h + m + s
},
就可以看到是這樣的效果啦~

4、參考文檔
這部分內(nèi)容參考官網(wǎng)文檔:https://element.eleme.cn/#/zh-CN/component/table
關(guān)于插槽的文檔:https://cn.vuejs.org/v2/guide/components-slots.html
關(guān)于日期格式的文檔:https://element.eleme.cn/#/zh-CN/component/date-picker#ri-qi-ge-shi