formatter elementui
Formatter in Element UI
Element UI provides a formatter function in various components like Table, Select, and DatePicker to customize the display format of data. The formatter allows transforming raw data into a more readable or desired format before rendering.
Using Formatter in Table Column
In the Table component, the formatter property can be used within a column definition to format cell content. It takes a function with parameters (row, column, cellValue, index) and returns the formatted value.
<el-table :data="tableData">
<el-table-column
prop="date"
label="Date"
:formatter="formatDate">
</el-table-column>
</el-table>
methods: {
formatDate(row, column, cellValue, index) {
return new Date(cellValue).toLocaleDateString();
}
}
Using Formatter in Select Options
For the Select component, the formatter can be used to customize the display of options. It is often combined with value-format to handle data transformations.
<el-select v-model="selected" :formatter="formatOption">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
methods: {
formatOption(value) {
return this.options.find(opt => opt.value === value)?.label || value;
}
}
Using Formatter in DatePicker
The DatePicker component allows formatting the displayed date using the format property. This is not exactly a formatter function but serves a similar purpose.
<el-date-picker
v-model="date"
type="date"
format="yyyy/MM/dd">
</el-date-picker>
Custom Formatter Logic
For more complex formatting, a custom function can be implemented. For example, formatting numbers with currency symbols or adding conditional styling.
methods: {
formatCurrency(row, column, cellValue) {
return `$${cellValue.toFixed(2)}`;
}
}
Key Considerations
- The
formatterfunction should be pure and avoid side effects. - Ensure the formatted output is compatible with the component's expectations (e.g., strings for display).
- Performance-intensive formatting should be memoized or optimized if used in large datasets.
By leveraging the formatter functionality, Element UI components can display data in a more user-friendly and context-appropriate manner.







