如何在Vue.js上创建带有日期标记的列表?

时间:2017-08-14 15:00:03

标签: javascript vue.js vuejs2

只是有这样的观点:

<div class="items">
    <div class="datemark" data-date="1">Today</div>
    <div class="item" data-date="1">Item 1</div>
    <div class="item" data-date="1">Item 2</div>
    <div class="item" data-date="1">Item 3</div>

    <div class="datemark" data-date="2">Tommorow</div>
    <div class="item" data-date="2">Item 1</div>
    <div class="item" data-date="2">Item 2</div>
    <div class="item" data-date="2">Item 3</div>
</div>

有这样的数据:

data = [
    1: {
        human: 'Today',
        date: 1,
        items: [
            item1: {
                name: 'test',
                date: 1 // possible here
            },
            item2: {...},
        ]
    },
    2: {
        human: 'Tommorow',
        date: 2,
        items: [
            item1: {...},
            item2: {...},
        ]
    }
]

或者可以是:

data = [
    item1: {
        name: 'test',
        date: 1 // possible here
    },
    item2: {
        name: 'other',
        date: 2 // possible here
    },
    ...
]

如何使其工作,并可以通过日期标记和内部排序desc / asc&#39;如果日期和分钟也有不同的日期和分钟吗?

尝试过v-for但只有简单的列表,如何使用日期标记?

谢谢!

1 个答案:

答案 0 :(得分:0)

你不必这样做,改为使用computed属性,你可以看到我使用slice,因为我想要复制数组而不是对元素进行排序:

&#13;
&#13;
const app = new Vue({
  el: '#app',
  data: {
    order: 'ASC',
    list: [
        {
            name: 'item1',
            date: 1 // possible here
        },
        {
            name: 'item2',
            date: 2 // possible here
        },
        {
            name: 'item3',
            date: 3 // possible here
        },
        {
            name: 'test',
            date: 4 // possible here
        },
        {
            name: 'other',
            date: 5 // possible here
        }
    ]
  },
  computed: {
      sortedList() {
          return this.list.slice(0)
            .sort((a, b) => {
                if (this.order === 'ASC') {
                    return b.date - a.date;
                }
                return a.date - b.date;
            })
      }
  },
  methods: {
      toggleSort(type){
          this.order = type;
      }
  }
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="app">
  <div>
    <button v-on:click="toggleSort('ASC')">ASC</button>
    <button v-on:click="toggleSort('DSC')">DSC</button>
  </div>
  <div>
    <div class="datemark" v-for="item in sortedList">
      <div class="item">{{item.name}}</div>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

供您参考,如果您实际在实际日期进行比较,请改用#34;

array.sort(function(a,b){
  // Turn your strings into dates, and then subtract them
  // to get a value that is either negative, positive, or zero.
  return new Date(b.date) - new Date(a.date);
});