简体   繁体   English

PrimeVue DataTable 列按日期/时间排序

[英]PrimeVue DataTable Column Sort by Date/Time

I have a PrimeVue DataTable ( https://primefaces.org/primevue/datatable ) that is arranged as such:我有一个 PrimeVue 数据表( https://primefaces.org/primevue/datatable ),其排列方式如下:

<DataTable
  :rows = "5"
  :value = "apiItems"
>
  <Column
    v-for="data in columns"
    :field="data.field"
    :header="data.header"
    :key="data.field"
    :sortable="true"
    />
</DataTable>

Where the table is being populated by data received from an API call, and the field layout is as listed:该表由从 API 调用接收的数据填充,并且字段布局如下所列:

const columns = [
  { field: 'initialDate', header: 'Initial Date'},
  { field: 'finishDate', header: 'Finish Date'}
];

The data being retrieved from the API is in the form of a JS Date() component that is displayed as such: "08/01/2022 08:33:32" for both initialDate and finishDate从 API 检索的数据采用 JS Date() 组件的形式,显示如下:initialDate 和 finishDate 均为“08/01/2022 08:33:32”

How can I the columns via ascending or descending by both the date AND time stamps, whereas now, sorting the columns just rearranges the values based on the first digits available, which happen to be the month;如何通过日期和时间戳的升序或降序来列,而现在,对列进行排序只是根据可用的第一个数字(恰好是月份)重新排列值; I need them to sort corresponding to not only the correct month, but the time as well.我需要它们不仅对应于正确的月份,而且还对应于时间。

Any help is appreciated, thanks.任何帮助表示赞赏,谢谢。

What you are receiving from the API cannot be a Date() object, but is probably a string .您从 API 收到的内容不能是Date() object,但可能是string And so, if you sort by this column, the rows are sorted lexicographically, but not chronologically.因此,如果您按此列排序,则行将按字典顺序排序,但不按时间顺序排序。

To avoid that, you should convert the data coming from the API into Date objects.为避免这种情况,您应该将来自 API 的数据转换为Date对象。 If you convert that to a timestamp, that's very convenient to sort by chronologically:如果将其转换为时间戳,则按时间顺序排序非常方便:

for (item of apiItems) {
  item.initialDateObj = new Date(item.initialDate)
  item.initialDateTimestamp = item.intialDateTimeObj.getTime()
}

You can then specify that as the field to sort a column by:然后,您可以将其指定为按以下方式对列进行排序的字段:

const columns = [
  { field: 'initialDate', sortField: 'initialDateTimestamp', header: 'Initial Date'},
  { field: 'finishDate', sortField: 'finishDateTimestamp', header: 'Finish Date'}
];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM