为什么我的排序数组脚本在Vue.js中不起作用



嗯,我在按日期排序这个表时遇到了问题。排序函数作为我们应该使用哪种排序的决定因素-有效,但排序函数已经不起作用了,我不知道为什么。

html:

<th @click = "sort('data_produktu')" class="date">Data</th>

数据:

messages: [],
currentSort:'data_produktu',
currentSortDir:'asc',

方法:

sort: function(s){

if(s === this.currentSort) {
this.currentSortDir = this.currentSortDir==='asc'?'desc':'asc';
}
this.currentSort = s;
console.log(this.messages);
}

计算:

sortedMessages:function() {
return this.messages.sort((a,b) => {
let modifier = 1;
if(this.currentSortDir === 'desc') modifier = -1;
if(a[this.currentSort] < b[this.currentSort]) return -1 * modifier;
if(a[this.currentSort] > b[this.currentSort]) return 1 * modifier;
return 0;
});
}

数组(console.log输出,因为我从DB中获取它(:

0: {id_komunikat: '4', data_produktu: '2022-08-12 20:05:30', tresc: 'Example info', typ: '2', status_komunikatu: '1', …}
1: {id_komunikat: '5', data_produktu: '2022-08-12 20:05:36', tresc: 'Example info', typ: '2', status_komunikatu: '1', …}
2: {id_komunikat: '6', data_produktu: '2022-08-12 20:05:39', tresc: 'Example info', typ: '2', status_komunikatu: '1', …}
3: {id_komunikat: '7', data_produktu: '2022-08-12 20:05:47', tresc: 'Example info', typ: '1', status_komunikatu: '1', …}

我看到data_produktudate,排序date不能排序,大于>或小于<,但要减去时间戳。

例如:

array.sort(function(a,b){
return new Date(b) - new Date(a);
});

计算的函数在我看来很可疑。它可能会导致无限循环,因为您还可以通过调用.sort()方法在适当的位置更改this.messages。我建议改为:

sortedMessages:function() {
//       use `.slice()` to clone first
this.messages.slice().sort((a, b) => ...)

最新更新