带日子标题的Vue v-for循环

时间:2019-02-13 22:15:17

标签: vue.js vuejs2

我正在将现有的日程表页面重新构建为Vue.JS应用,而我试图以类似以下DOM的形式结束。 (我是Vue的新手,并且已经看到了很多v-for循环的示例,但是我想知道如何甚至满足我的特定循环要求。)

<ul class="days">
  <li class="day">
    Feb 14
    <ul class="events">
      <li class="event">Event 1</li>
      <li class="event">Event 2</li>
    </ul>
  </li>
  <li class="day">
    Feb 15
    <ul class="events">
      <li class="event">Event 3</li>
    </ul>
  </li>
</ul>

我的数据当前结构如下:

events: [
  {
    "Name": "Event 1",
    "StartDateTime": "February 14, 2019 08:00:00"
  },
  {
    "Name": "Event 2",
    "StartDateTime": "February 14, 2019 09:00:00"
  },
  {
    "Name": "Event 3",
    "StartDateTime": "February 15, 2019 08:00:00"
  }
]

我应该使用普通的JS遍历数据,将每个StartDateTime转换为一天,对结果进行过滤以确保没有重复项,然后将该数据作为单独的days对象存储在Vue数据中,然后执行一些操作嵌套的v-for首先是几天,然后是当天发生的事件?我如何告诉嵌套事件v-for以匹配日期?还是有一种更好的Vue方法来处理整个问题?谢谢!

1 个答案:

答案 0 :(得分:2)

使用computed property返回一个数据结构,该结构便于迭代按日期分组的事件数据。以下代码使用Array.prototype.reduce()创建查找Object,其中的键是从每个事件的StartDateTime解析的日期,值是相应日期内的事件数组:

computed: {
  eventDates() {
    return this.events.reduce((p,c) => {
      const date = new Date(c.StartDateTime).toDateString();
      p[date] = p[date] || [];
      p[date].push(c);
      return p;
    }, {});
  }
},

然后在模板中,使用v-for with that Object

<ul class="days">
  <li class="day" v-for="(events, date) in eventDates">
    {{date}}
    <ul class="events">
      <li class="event" v-for="event in events">{{event.Name}}</li>
    </ul>
  </li>
</ul>

new Vue({
  el: '#app',
  data: () => ({
    events: [
      {
        "Name": "Event 1",
        "StartDateTime": "February 14, 2019 08:00:00"
      },
      {
        "Name": "Event 2",
        "StartDateTime": "February 14, 2019 09:00:00"
      },
      {
        "Name": "Event 3",
        "StartDateTime": "February 15, 2019 08:00:00"
      }
    ]
  }),
  computed: {
    eventDates() {
      return this.events.reduce((p,c) => {
        const date = new Date(c.StartDateTime).toDateString();
        p[date] = p[date] || [];
        p[date].push(c);
        return p;
      }, {});
    },
  }
})
<script src="https://unpkg.com/vue@2.6.5/dist/vue.min.js"></script>

<div id="app">
  <ul class="days">
    <li class="day" v-for="(events, date) in eventDates">
      {{date}}
      <ul class="events">
        <li class="event" v-for="event in events">{{event.Name}}</li>
      </ul>
    </li>
  </ul>
</div>