Vue - 对于每一个v-for项目运行方法

8
我通过v-for循环遍历日历中的日期: <ul><li v-for="day in daysInMonth"></li></ul> 在Firebase中,我存储了事件。每个事件都有一个日期属性:
eVeNtKeY
  date: 12/7/17

现在,每天可能没有事件,但我需要获取每天的事件计数。通过 Firebase 调用,我下载了整个月的所有事件,并将其保存在 Vue 的 data 中作为数组 thisMonthsEvent

data: {
  thisMonthsEvents: [bunch of firebase data],
  currentMonth: number
}

有没有一种方法可以在每次v-for循环重复时运行一个方法? 在我的想法中,我可以这样做:

    computed: {
        eventsByDay () {
          return this.thisMonthsEvents.filter(function (event) {
            return event.date === this.currentMonth + '-' + Somehow get the day from loop + '-2017'
});
        }
      }

将当前日期作为方法eventsByDay(day)的参数添加,并在其中使用它;还要在v-for循环中传递它:<li v-for="day in daysInMonth">{{ eventsByDay(day) }}</li> - Egor Stambakio
1个回答

10

使用方法替代计算属性,在 v-for 循环中直接调用该方法,将 day 变量作为参数传递:

methods: {
  getEventsByDay(day) {
    return this.thisMonthsEvents.filter(function (event) {
      return event.date === this.currentMonth + '-' + day + '-2017'
    });
  }
}

:空段落标签。
<li v-for="day in daysInMonth">
  {{ getEventsByDay(day) }}
</li>

太好了!我只需要添加.length就可以得到计数了。 - Auzy
当我尝试这样做时,我得到了Property or method "myMethod" is not defined on the instance but referenced during render的错误。该模板嵌套在其他几个模板中。@thanksd - Kirk Ross
嘿 @KirkRoss,我在我的示例中没有定义 myMethod 方法,所以如果你引用了该名称的方法但没有在该模板组件的 methods 对象中定义它,你将会得到那个错误。 - thanksd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接