如何从计算值循环每月的每一天

时间:2018-04-07 16:54:55

标签: javascript vue.js vuejs2

我正在创建一个注册表单,用户必须在其中选择出生日期。

我正在循环查看月份和输出日的列表。

let selectedMonth = 'April'

new Vue ({
  el: '#app',
  data: {
    months: [
      {month: 'January', days: 31},
      {month: 'February', days: 28},
      {month: 'March', days: 31},
      {month: 'April', days: 30},
      {month: 'May', days: 31},
      {month: 'June', days: 30},
      {month: 'July', days: 31},
      {month: 'August', days: 31},
      {month: 'September', days: 30},
      {month: 'October', days: 31},
      {month: 'November', days: 30},
      {month: 'December', days: 31},
    ]
  },
  computed: {
    filterDays() {
      return this.months.filter(function(value) {
        return value.month === selectedMonth;
      });
    }
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>  

<div id = "app">
  <select id="dob">
    <option v-for="day in filterDays" :value="day.days">{{ day.days }}</option>
  </select>
</div>

上述程序只输出<option value = "30">30</option>而不是循环day in 30

1 个答案:

答案 0 :(得分:2)

filterDays返回月份对象集合。如果要循环使用数字,请将其用作循环源:filterDays[0].days

<option v-for="day in filterDays[0].days" :value="day">{{ day }}</option>

或者通过返回那里的日期来修复计算函数。

computed: {
  filterDays() {
    // Select the first item here.
    const month = this.months.filter(value => value.month === selectedMonth)[0];

    // If the month was found, return its days, otherwise, undefined.
    return month && month.days;
  }
},