首页 > 解决方案 > 如何在 vue js 中嵌套循环和数组?

问题描述

我从控制器查询的结果

date: {2020-09-24: {work_hours: 7}, 2020-09-30: {work_hours: 8}}
2020-09-24: {work_hours: 7}
2020-09-30: {work_hours: 8}

这是我正在尝试嵌套 for 循环的 vue,但我得到的循环结果是原来的两倍

<table class="table table-hover table-bordered table-sm" >
  <thead>
      <tr>
        <template  v-for="disp in iDate.slice(1)">           
          <th scope="col" v-if="toWordDay(disp.date) == 'Sunday'" style="color:red">{{disp.date | forThDate}}</th>
          <th scope="col" v-else>{{disp.date | forThDate}}</th>
        </template>                           
      </tr>
  </thead>
  <tbody>
    <template v-for="fetch in attendanceData">
      <tr>
        <template v-for="disp in iDate.slice(1)">                
          <td style="height:10px;"  v-for="(data,ind) in fetch.date" v-if="ind == disp.date" >{{data.work_hours}}</td>  
          <td style="height:10px;" v-else>0</td>                          
        </template>                                  
      </tr>
    </template>

  </tbody>
</table>

标签: javascriptvue.jsv-for

解决方案


在不知道attendanceDataor的情况下iDate,我假设fetch.date您的意思是Result of my query from the controller,它是一个以日期为键的对象。您可以disp.date用作访问器密钥。

<table class="table table-hover table-bordered table-sm" >
  <thead>
      <tr>
        <template  v-for="disp in iDate.slice(1)">           
          <th scope="col" v-if="toWordDay(disp.date) == 'Sunday'" style="color:red">{{disp.date | forThDate}}</th>
          <th scope="col" v-else>{{disp.date | forThDate}}</th>
        </template>                           
      </tr>
  </thead>
  <tbody>
    <template v-for="fetch in attendanceData">
      <tr>
        <template v-for="disp in iDate.slice(1)">                
          <td style="height:10px;">
             <template v-if="fetch.date[disp.date]">
               {{fetch.date[disp.date].work_hours || 0}}
             </template> 
             <template v-else>0</template>
          </td>
        </template>                                  
      </tr>
    </template>

  </tbody>
</table>

推荐阅读