问题描述:
设计了一个比较复杂的表格,期望统一保留小数位数,不想使用插槽一行行的slot-scope="text"
定义数据。或者是在每行columns头定义 customCell
{
title: '体重阶段',
dataIndex: 'weight',
customCell: (record) => {
let weight = record.initialBw + "~" + record.finalBw
return {
domProps: {
innerHTML: weight,
},
};
},
width: 130,
},
实现效果(统一保留两位小数):
解决方案:
<a-table
:columns="renderColumns(metabolicProteinColumns)"
:data-source="metabolicProtein"
bordered
size="middle"
:scroll="{ y: 400 }"
:pagination="false"
class="tableItem"
style="margin-bottom: 20px"
>
</a-table>
export default {
const metabolicProteinColumns = [
{
title: '',
dataIndex: 'name',
key: 'name',
width: 100,
fixed: 'left',
},
{
title: "代谢能(Mcal/d)",
children: [
{
title: "供应量",
dataIndex: "supply",
},
{
title: "需求量",
dataIndex: "demand",
},
{
title: "差异",
dataIndex: "difference",
},
],
},
{
title: "代谢蛋白(Mcal/d)",
children: [
{
title: "供应量",
dataIndex: "supplyC",
},
{
title: "需求量",
dataIndex: "demandC",
},
{
title: "差异",
dataIndex: "differenceC",
},
],
},
];
data() {
return {
metabolicProteinColumns,
};
},
mounted() {},
methods: {
reserveDecimal(param, digit) {
// 传入参数 小数位数
let reg = /^[+-]?(\d|([1-9]\d+))(\.\d+)?$/;
if (param === null) {
return null
} else {
// 判断是否是数字('123',或123)
if (param !== 0 && reg.test(param) && typeof (param) === 'number') {
if (!digit) {
// eslint-disable-next-line no-param-reassign
digit = 0
}
return param.toFixed(digit);
} else {
// 字符串直接返回
return param;
}
}
// return param
}
},
renderColumns(columns) {
return columns.map((item) => {
return {
...item,
customCell(record) {
for (let key in record) {
record[key] = reserveDecimal(record[key], 2);
}
return record;
},
};
});
},
};