問題描述:
vue3中 element plus 中 el-table 的 el-table-column使用了插槽后,為什么sortable不起效果,不能點擊排序
<el-table-columnlabel="記賬日期"width="110"fixed="left"header-align="left"sortableshow-overflow-tooltip><template #default="scope">{{ formatDate(scope.row.jzDatetime, "YYYY-MM-DD") }}</template></el-table-column>
在 Element Plus 的?el-table
?中,當?el-table-column
?使用插槽自定義內容時,若未指定?prop
?屬性,會導致?sortable
?排序功能失效。因為表格需要根據?prop
?確定排序的字段。即使內容經過格式化,排序仍基于原始數據字段。
解決方案:為?el-table-column
?添加?prop
?屬性,指向對應的數據字段名:
vue
復制
下載
<el-table-columnprop="jzDatetime" <!-- 添加 prop 指定排序字段 -->label="記賬日期"width="110"fixed="left"header-align="left"sortableshow-overflow-tooltip ><template #default="scope">{{ formatDate(scope.row.jzDatetime, "YYYY-MM-DD") }}</template> </el-table-column>
注意事項:
-
數據類型正確性:確保?
jzDatetime
?字段的值是適合排序的類型(如時間戳或?Date
?對象)。若為字符串,需保證格式可直接比較(如?YYYY-MM-DD
)。 -
自定義排序規則:若需按格式化后的值排序(如字符串日期),可使用?
sort-method
?自定義排序邏輯:vue
復制
下載
<el-table-column:sort-method="(a, b) => customSort(a.jzDatetime, b.jzDatetime)"<!-- 其他屬性 --> >
js
復制
下載
const customSort = (a, b) => {// 實現自定義排序邏輯return new Date(a) - new Date(b); };
添加?prop
?后,表格即可根據指定字段觸發默認排序,點擊表頭即可正常排序。
<el-table-columnprop="jzDatetime"label="記賬日期"width="110"fixed="left"header-align="left"sortableshow-overflow-tooltip><template #default="scope">{{ formatDate(scope.row.jzDatetime, "YYYY-MM-DD") }}</template></el-table-column>