在 Vue 3 中使用 Element Plus 的?<el-table>
?組件時,如果你想增加自定義排序邏輯,可以通過以下幾個步驟實現:
1. 使用?default-sort
?屬性
首先,你可以在?<el-table>
?組件上使用?default-sort
?屬性來指定默認的排序規則。例如,如果你想默認按照某一列升序排序,可以這樣做:
<template><el-table :data="tableData" default-sort="{prop: 'date', order: 'ascending'}"><el-table-column prop="date" label="日期" sortable /><el-table-column prop="name" label="姓名" /><el-table-column prop="address" label="地址" /></el-table>
</template>
2. 使用?sort-method
?或?sort-comparator
?屬性
對于自定義排序邏輯,你可以使用?sort-method
?或?sort-comparator
?屬性。sort-method
?適用于簡單的比較函數,而?sort-comparator
?適用于更復雜的排序邏輯,比如異步排序。
使用?sort-method
<template><el-table :data="tableData"><el-table-column prop="date" label="日期" sortable :sort-method="dateSortMethod" /><el-table-column prop="name" label="姓名" /><el-table-column prop="address" label="地址" /></el-table>
</template><script setup>
import { ref } from 'vue';const tableData = ref([...]); // 你的數據數組const dateSortMethod = (a, b) => {return new Date(a) - new Date(b); // 示例:按日期字符串排序
};
</script>
使用?sort-comparator
(適用于 Element Plus)
<template><el-table :data="tableData"><el-table-column prop="date" label="日期" sortable :sort-comparator="dateComparator" /><el-table-column prop="name" label="姓名" /><el-table-column prop="address" label="地址" /></el-table>
</template><script setup>
import { ref } from 'vue';const tableData = ref([...]); // 你的數據數組const dateComparator = (a, b) => {return new Date(a.date) - new Date(b.date); // 按日期對象排序,確保數據對象中有 date 屬性
};
</script>
3. 使用?sort-change
?事件自定義排序行為(動態排序)
如果你需要在用戶點擊列頭進行排序時執行更復雜的邏輯,可以使用?sort-change
?事件。這個事件會在列頭排序變化時觸發,你可以在這個事件處理函數中實現自定義的排序邏輯。
<template><el-table :data="tableData" @sort-change="handleSortChange"><el-table-column prop="date" label="日期" sortable /><el-table-column prop="name" label="姓名" /><el-table-column prop="address" label="地址" /></el-table>
</template><script setup>
import { ref } from 'vue';const tableData = ref([...]); // 你的數據數組
const handleSortChange = ({ column, prop, order }) => {if (prop === 'date') {// 根據日期進行排序的自定義邏輯,例如使用 lodash 的 sortBy 或其他方法進行排序。// 這里僅作為示例,實際應根據需求調整排序邏輯。if (order === 'ascending') {tableData.value.sort((a, b) => new Date(a[prop]) - new Date(b[prop]));} else if (order === 'descending') {tableData.value.sort((a, b) => new Date(b[prop]) - new Date(a[prop]));} else { // order 為 null 表示取消排序,重置數據等邏輯可在此處理。// 重置數據或按其他邏輯處理。}}
};
</script>