在 Vue 3 中使用 Element Plus 的?<el-table>
?組件時,如果你希望去除表格列中的小數,你可以通過幾種方式來實現:
1. 使用?formatter
?屬性
<el-table-column>
?組件的?formatter
?屬性允許你自定義單元格的顯示格式。你可以使用這個屬性來格式化數據,去除小數。
<template><el-table :data="tableData" style="width: 100%"><el-table-column prop="id" label="ID" width="180"></el-table-column><el-table-column prop="name" label="Name" width="180"></el-table-column><el-table-column prop="amount" label="Amount" :formatter="formatAmount"></el-table-column></el-table>
</template><script setup>
import { ref } from 'vue';const tableData = ref([{ id: 1, name: 'Item 1', amount: 123.45 },{ id: 2, name: 'Item 2', amount: 67.89 },{ id: 3, name: 'Item 3', amount: 10.11 }
]);const formatAmount = (row, column, cellValue, index) => {return Math.floor(cellValue); // 去除小數,向下取整
};
</script>
2. 使用計算屬性或方法
如果你不想在模板中使用復雜的邏輯,你可以在組件的?setup
?方法中使用計算屬性或方法來處理數據。
<template><el-table :data="processedTableData" style="width: 100%"><el-table-column prop="id" label="ID" width="180"></el-table-column><el-table-column prop="name" label="Name" width="180"></el-table-column><el-table-column prop="amount" label="Amount"></el-table-column></el-table>
</template><script setup>
import { ref, computed } from 'vue';const tableData = ref([{ id: 1, name: 'Item 1', amount: 123.45 },{ id: 2, name: 'Item 2', amount: 67.89 },{ id: 3, name: 'Item 3', amount: 10.11 }
]);const processedTableData = computed(() => {return tableData.value.map(item => ({...item,amount: Math.floor(item.amount) // 去除小數,向下取整}));
});
</script>
3. 直接修改數據源(不推薦)
雖然直接修改數據源可以達到目的,但這通常不是最佳實踐,因為它違反了響應式數據更新的原則。更好的方式是使用上述的?formatter
?或計算屬性方法。但如果你確實需要在數據加載到表格之前就處理這些數據,你可以這樣做:
tableData.value = tableData.value.map(item => ({...item,amount: Math.floor(item.amount) // 在這里處理數據
}));
推薦使用?formatter
?屬性或計算屬性方法來處理顯示格式,這樣可以保持數據的響應式和組件的清晰度。直接修改數據源雖然在某些情況下可行,但不是最佳實踐。