如何使用 Vue.js 2 按日期对数组进行排序

新手上路,请多包涵

是否有按日期或格式化日期对数组进行排序的函数或方法?

 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>

原文由 radeveloper 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 838
2 个回答

只需要这样做,所以我会写下最简单的解决方案:

 ...
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))
  }
}
...

原文由 peaceman 发布,翻译遵循 CC BY-SA 3.0 许可协议

通常情况下,你需要这样的东西:

 /** ...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 规范,它将 在此处 链接到日期时间 ISO 8601 格式

快速说明:

 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

原文由 Amresh Venugopal 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题