vue3+element-plus表格默认排序default-sort失效问题
vue3+element-plus表格默认排序default-sort失效问题
·
场景
在使用动态数据渲染的场景,el-table设置默认属性default-sort失效。
原因
el-table的default-sort属性是针对静态数据的,如果是动态数据,default-sort则无法监听到。
- 案例:静态数据
<template>
<el-table
:data="tableData"
:default-sort="{ prop: 'date', order: 'descending' }"
style="width: 100%"
>
<el-table-column prop="date" label="Date" sortable width="180" />
<el-table-column prop="name" label="Name" width="180" />
<el-table-column prop="address" label="Address" />
</el-table>
</template>
<script lang="ts" setup>
interface User {
date: string
name: string
address: string
}
const tableData: User[] = [
{
date: '2016-05-03',
name: 'Tom',
address: 'No. 189, Grove St, Los Angeles',
},
{
date: '2016-05-02',
name: 'Tom',
address: 'No. 189, Grove St, Los Angeles',
},
{
date: '2016-05-04',
name: 'Tom',
address: 'No. 189, Grove St, Los Angeles',
},
{
date: '2016-05-01',
name: 'Tom',
address: 'No. 189, Grove St, Los Angeles',
},
]
</script>
默认排序正常
- 案例:模拟动态数据(setTimeout模拟后端延时数据返回)
<template>
<el-table
ref="tableNode"
:data="tableData"
:default-sort="{ prop: 'date', order: 'descending' }"
style="width: 100%"
>
<el-table-column prop="date" label="Date" sortable width="180" />
<el-table-column prop="name" label="Name" width="180" />
<el-table-column prop="address" label="Address" />
</el-table>
</template>
<script lang="ts" setup>
import { ref, nextTick } from 'vue'
const tableNode = ref()
interface User {
date: string
name: string
address: string
}
let tableData = ref<User[]>([])
setTimeout(function(){
tableData.value = [
{
date: '2016-05-01',
name: 'Tom',
address: 'No. 189, Grove St, Los Angeles',
},
{
date: '2016-05-03',
name: 'Tom',
address: 'No. 189, Grove St, Los Angeles',
},
{
date: '2016-05-02',
name: 'Tom',
address: 'No. 189, Grove St, Los Angeles',
},
{
date: '2016-05-04',
name: 'Tom',
address: 'No. 189, Grove St, Los Angeles',
}
]
}, 3000)
</script>
默认排序失效
解决方法
等待数据渲染结束后(nextTick回调),采用el-table提供的sort方法实现手动排序
<template>
<el-table
ref="tableNode"
:data="tableData"
:default-sort="{ prop: 'date', order: 'descending' }"
style="width: 100%"
>
<el-table-column prop="date" label="Date" sortable width="180" />
<el-table-column prop="name" label="Name" width="180" />
<el-table-column prop="address" label="Address" />
</el-table>
</template>
<script lang="ts" setup>
import { ref, nextTick } from 'vue'
const tableNode = ref()
interface User {
date: string
name: string
address: string
}
let tableData = ref<User[]>([])
setTimeout(async function(){
tableData.value = [
{
date: '2016-05-01',
name: 'Tom',
address: 'No. 189, Grove St, Los Angeles',
},
{
date: '2016-05-03',
name: 'Tom',
address: 'No. 189, Grove St, Los Angeles',
},
{
date: '2016-05-02',
name: 'Tom',
address: 'No. 189, Grove St, Los Angeles',
},
{
date: '2016-05-04',
name: 'Tom',
address: 'No. 189, Grove St, Los Angeles',
}
]
await nextTick()
tableNode.value.sort('date', 'descending')
}, 3000)
</script>
默认排序正常
更多推荐
已为社区贡献1条内容
所有评论(0)