【问题标题】:How to sort an array by date using Vue.js 2如何使用 Vue.js 2 按日期对数组进行排序
【发布时间】:2017-07-02 16:18:00
【问题描述】:

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

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>

【问题讨论】:

    标签: arrays sorting datetime vue.js


    【解决方案1】:

    不得不这样做,所以我会写下最简单的解决方案:

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

    【讨论】:

    • 谢谢,也帮助了我。
    • 我需要像 new Date(a.date).getDate() 一样添加 getDate()
    【解决方案2】:

    一种解决方案可以是:

    1. 将未格式化的日期添加为帮助字段。
    2. 使用 momentJS 根据您的格式化日期创建时刻对象。
    3. 对其进行排序,例如基于这些答案:Sort Javascript Object Array By Date

    【讨论】:

      【解决方案3】:

      通常,您需要以下内容:

      /** ...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

      【讨论】:

        猜你喜欢
        • 2016-11-07
        • 1970-01-01
        • 1970-01-01
        • 2013-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-10
        • 1970-01-01
        相关资源
        最近更新 更多