在使用动态数据渲染的场景,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>
<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>