Vue.js:如何循环开始时间以将结束时间与var x相乘

问题描述

我有数据start_time,end_time,x和结果。我想在选择选项中显示它,第一个选项是初始数据start_time,并继续循环变量x的倍数,直到值等于end_time为止。这是期望。

enter image description here

这是我的观点:

<select class="form-control">
    <option>08:00:00</option>
    <option>08:15:00</option>
    <option>08:30:00</option>
    <option>08:45:00</option>
    <option>09:00:00</option>
    <option>...</option>
    <option>19:00:00</option>
</select>

这是我的代码

data: function () {
    return {
        start_time: '08:00:00',end_time: '19:00:00',x: 15,result:'',}
},computed:{
}

解决方法

您可以做的是创建一个计算属性,该属性将在给定start_timeend_time约束的情况下返回所有可用时间选项的数组。然后使用<option/>将其循环到您的v-for元素。

  <select class="form-control">
    <option v-for="(time,index) in times" :key="index">{{time}}</option>
  </select>
computed: {
  times() {
    // transform the start_time and end_time to Date for easier comparison.
    let startTime = new Date(`1/1/1970 ${this.start_time}`);
    const endTime = new Date(`1/1/1970 ${this.end_time}`);

    // This interval is in Minutes.
    const interval = this.x * 60000;

    // The result array where we will store the time
    const results = [];

    while (startTime.getTime() <= endTime.getTime()) {
      results.push(`${this.formatTime(startTime)}`);
      startTime = new Date(startTime.getTime() + interval);
    }

    return results;
  }
},methods: {
  formatTime(date) {
    // format the date here...
    return '00:00:00';
  }
}

对于格式化日期,您可以使用第三方库来完成工作,也可以使用原始javascript。

formatTime(date) {
  const hours = date.getHours().toString().padStart(2,"0");
  const minutes = date.getMinutes().toString().padStart(2,"0");
  const seconds = date.getSeconds().toString().padStart(2,"0");
  return `${hours}:${minutes}:${seconds}`;
}

这里是工作中的demo