Vue3 Element Plus el-table-column Sortable 排序失效
问题描述:
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>