[英]Why my sorting array script not working in Vue.js?
好吧,我在按日期排序此表時遇到問題。 排序 function 作為我們應該使用哪種排序的決定因素 - 有效,但排序 function 不再有效,我不知道為什么。
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 output,因為我從數據庫中獲取它):
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_produktu
是一個date
,排序date
無法排序,大於>
或小於<
,但通過減去時間戳。
前任:
array.sort(function(a,b){
return new Date(b) - new Date(a);
});
計算出來的 function 在我看來很可疑。 它可能會導致無限循環,因為您還可以通過調用.sort()
方法就地改變this.messages
。 我建議將其更改為:
sortedMessages:function() {
// use `.slice()` to clone first
this.messages.slice().sort((a, b) => ...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.