ElementUI 码表-elementui table formatter
在使用ElementUI的表格组件(Table)时,我们可能会遇到这样一个问题:表格中的某些数据需要按照特定格式展示给用户,比如将状态码转换为对应的描述文字、金额数值添加千分位等。解决方案是利用elementui table 的formatter属性来对表格列的数据进行格式化。
一、基础用法
对于简单的格式化需求,可以直接在定义表格列时使用formatter函数。例如,假设我们有一个用户列表,其中包含用户的状态(0表示禁用,1表示启用),我们希望在表格中显示“禁用”或“启用”而不是数字。
javascript
// 定义表格列
columns: [
{
label: '用户状态',
prop: 'status',
formatter: function(row, column, cellValue) {
return cellValue === 1 ? '启用' : '禁用';
}
},
// 其他列...
]
二、复杂格式化 - 使用外部方法
当格式化逻辑较为复杂时,可以将格式化逻辑提取到外部方法中。这有助于保持代码整洁,并且可以在多个地方复用相同的格式化规则。例如,处理日期格式化:
html
<!-- 其他列... -->
</p>
export default {
methods: {
dateFormat(row, column, cellValue) {
if (!cellValue) return '';
const date = new Date(cellValue);
const year = date.getFullYear();
const month = ('0' + (date.getMonth() + 1)).slice(-2);
const day = ('0' + date.getDate()).slice(-2);
return `${year}-${month}-${day}`;
}
},
data() {
return {
tableData: [
{ date: '2023-05-18T00:00:00.000Z' },
// 其他数据项...
]
};
}
};
<p>
三、自定义渲染 - slot-scope
除了使用formatter属性,还可以通过slot - scope实现更灵活的自定义渲染。这种方法允许我们在模板中编写任意复杂的HTML结构和逻辑。
html
<template>
<el-table :data="tableData">
<el-table-column label="操作">
<template slot-scope="scope">
<el-button @click="handleEdit(scope.row)" type="text" size="small">编辑</el-button>
<el-button @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>
</template>
</el-table-column>
<!-- 其他列... -->
</el-table>
</template>
以上三种方式可以根据实际场景选择使用,它们都能很好地解决elementui表格中数据格式化的问题。无论是简单的值映射还是复杂的业务逻辑处理,都可以找到合适的解决方案。