elementui formatter
ElementUI 的 formatter 用法
ElementUI 的 formatter 是一个常用于表格(el-table)和表单(el-form)中的属性或方法,用于格式化显示数据。以下是几种常见的使用场景和示例:
表格列中的 formatter
在 el-table-column 中,formatter 是一个函数,用于自定义单元格内容的显示格式。
<el-table :data="tableData">
<el-table-column
prop="date"
label="日期"
:formatter="formatDate">
</el-table-column>
</el-table>
<script>
export default {
methods: {
formatDate(row, column, cellValue) {
return cellValue ? new Date(cellValue).toLocaleDateString() : '-';
}
}
}
</script>
表单输入框的 formatter
在 el-input 或其他表单组件中,formatter 通常与 parser 配对使用,用于格式化输入和解析值。
<el-input
v-model="price"
:formatter="formatPrice"
:parser="parsePrice">
</el-input>
<script>
export default {
methods: {
formatPrice(value) {
return `¥${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
},
parsePrice(value) {
return value.replace(/¥|,/g, '');
}
}
}
</script>
表格中的 formatter 结合插槽
如果需要更复杂的格式化,可以结合插槽使用。
<el-table-column prop="status" label="状态">
<template #default="{ row }">
<el-tag :type="row.status === 'success' ? 'success' : 'danger'">
{{ row.status }}
</el-tag>
</template>
</el-table-column>
注意事项
formatter在表格中通常接收三个参数:row(当前行数据)、column(列信息)、cellValue(单元格值)。- 在表单中,
formatter和parser需要配合使用,确保数据的一致性。 - 对于复杂格式化需求,插槽方式更灵活。
通过合理使用 formatter,可以轻松实现数据的自定义显示和输入格式化。







