在element-UI table中实现金额和时间格式化:
有时候element-UI table中,我们需要将后端给的金额或时间需要额外处理来展示,比如将金额60000.06处理成60,000.00这种格式,再比如将时间格式化,怎么来实现呢:
<el-table-column prop="loanAmt" label="放款金额">
<template slot-scope="scope">
<span>{{scope.row.loanAmt | formatStatus}}</span>
</template>
</el-table-column>
<el-table-column prop="loanDate" label="放款日期">
<template slot-scope="scope">
<span>{{scope.row.loanDate | formatterDate}}</span>
</template>
</el-table-column>
首先,我们看看slot-scope="scope":
slot-scope="scope" 来取得作用域插槽:data绑定的数据,scope可以随便替换其他名称,只是定义对象来代表取得的data数据。
然后,<span>{{scope.row.loanAmt | formatStatus}}</span>这里scope.row.loanAmt就是一个金额,然后通过filters(过滤器)去处理格式化:
filters: {
formatStatus: function(val) {
return toThousandslsFilter(val, 2);
},
formatterDate: function(val) {
if (val) {
let txt = val.slice(0, 10);
return txt.slice(0, 4) + "-" + txt.slice(4, 6) + "-" + txt.slice(6, 8);
} else {
return "";
}
},
}
ok,再看看toThousandslsFilter是怎么处理的:
toThousandslsFilter(num, digits) {
num = (num + '').replace(/\,/g, '')
return (+num || 0).toFixed(digits).toString().replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
}
通过这个案例主要说了两点:
1、在el-table中怎么获取值
2、filters(过滤器)怎么来用