是否有按日期或格式化日期对数组进行排序的功能或方法?
var sortbydate = new Vue({
el: '#sortbydate',
data: {
items: [
{ codeName: 'Looper', date: '25.03.1980' },
{ codeName: 'Sweetze', date: '25.03.1981' },
{ codeName: 'Lycon', date: '01.08.1991' }
]
}
})
<ul id="sortbydate">
<li v-for="(item, index) in items" style="list-style:none">
{{ index }} - {{ item.codeName }}
</li>
</ul>
答案 0 :(得分:7)
只需这样做,所以我会写下最简单的解决方案:
...
computed: {
sortedItems: function() {
this.items.sort( ( a, b) => {
return new Date(a.date) - new Date(b.date);
});
return this.items;
}
}
...
或者如果你想要一个班轮
...
computed: {
sortedItems: function() {
return this.items.sort((a, b) => new Date(a.date) - new Date(b.date))
}
}
...
答案 1 :(得分:1)
一种解决方案可以是:
答案 2 :(得分:1)
通常,您需要以下内容:
/** ...somewhere inside a method of your component
* but it is always better to keep such functions in a services folder
* you could not only need it elsewhere, but at the same time, it maintains the purpose
* of your component too. */
// assuming you want it in ascending order
this.items.sort((a, b) => {
if (Date.parse(a.date) > Date.parse(b.date)) {
return 1
} else if (Date.parse(a.date) < Date.parse(b.date)) {
return -1
} else {
return 0
}
})
但是这不适用于您的情况,因为您的格式不符合Date.parse
spec,这会将您链接到日期时间ISO 8601格式here
快速说明:
new Date('25.03.1980') // Invalid Date (Throws an error if your date is incorrect)
Date.parse('25.03.1980') // NaN, using (Date.parse will not throw error!)
因此,如果可能,您需要更改格式,或者使用库,我建议momentjs。