在開發中遇到了這樣一個問題,就是接好接口以后數據庫中傳入的值為'true'和'false'這樣的布爾值或者是'0' , '1' , '2'這樣數字,還有一種是傳入的是時間戳也就是類似'1575949565559'這樣子,而實際上他們是有相對應的中文值的,這里提供一種轉換的思路。
- 布爾類型轉換
- 數字類型轉換
- 時間戳轉換
1、布爾類型轉換
一般來說像這種返回結果,在數據庫中存儲的值都是布爾類型的。例:
而我想要的效果是
其實很簡單,在el-table-column中加入一個<template slot-scope="scope"></template>就可以實現。這應該是文檔中關于插槽的內容。
我實現的代碼:注意prop值要相對應
<el-table-column label="登錄結果" prop="result" align="center" width="130px">
<template slot-scope="scope">{{ !!(scope.row.result)?'成功':'不成功' }}</template>
</el-table-column>
2、數字類型
同樣我又遇到了另外一個問題,就是當傳過來的值是數字類型的話怎樣用三元運算符來解決呢。可以看到接口中傳入的是數字。
實際上我想要的是
實現代碼有兩種:
一是類似布爾類型,在三元運算符中加入判斷,以及嵌套實現。
<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存儲根據map的值來對應轉換的數據
data() {
return {
map: {
1: '表單',
2: '列表',
3: '列表和打印'
}
}
},
3、時間戳轉換
我又遇到了一個從數據庫中導入時間后,顯示的是這樣的= =什么鬼,查了一下原來是時間戳。這里一起寫了解決方法。
HTML中的代碼:利用element-UI 的 formatter 進行轉換
<el-table-column label="創建時間" prop="createTime" :formatter="timestampToTime" align="center" width="140" />
在methods中寫一個 timestampToTime 這樣的方法
// 時間戳轉化為時間
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、參考文檔
這部分內容參考官網文檔:https://element.eleme.cn/#/zh-CN/component/table
關于插槽的文檔:https://cn.vuejs.org/v2/guide/components-slots.html
關于日期格式的文檔:https://element.eleme.cn/#/zh-CN/component/date-picker#ri-qi-ge-shi