我有两组数据。
时间持续时间列表
timeDurations: [
{ 'duration': '02:30 AM - 03:00 AM' },
{ 'duration': '03:00 AM - 03:30 AM' },
{ 'duration': '03:30 AM - 04:00 AM' },
{ 'duration': '04:00 AM - 04:30 AM' },
{ 'duration': '04:30 AM - 05:00 AM' },
{ 'duration': '05:00 AM - 05:30 AM' },
{ 'duration': '05:30 AM - 06:00 AM' }
];
分配到该特定持续时间的总线列表
assignedBus: [
{ 'duration': '03:00 AM - 03:30 AM', 'bus': 'Bus1' },
{ 'duration': '04:00 AM - 04:30 AM', 'bus': 'Bus2' },
{ 'duration': '05:00 AM - 05:30 AM', 'bus': 'Bus3' }
];
我正在使用表格来显示使用vue js的时间持续时间列表
<table class="table table-striped table-bordered table-hovered">
<thead>
<tr>
<th>Time Duration</th>
<th>Bus</th>
</tr>
</thead>
<tbody>
<tr v-for="time in timeDurations">
<td>{{time.duration}}</td>
<td><button class="btn btn-primary">Assign Bus</button></td>
</tr>
</tbody>
</table>
但实际上,我想根据assignedBus
数据
表中的值必须像这样
| Time Durations | Action |
| 02:30 AM - 03:00 AM | Assign Bus |
| 03:00 AM - 03:30 AM | View Bus |
| 03:30 AM - 04:00 AM | Assign Bus |
| 04:00 AM - 04:30 AM | View Bus |
| 04:30 AM - 05:00 AM | Assign Bus |
| 05:00 AM - 05:30 AM | View Bus |
| 05:30 AM - 06:00 AM | Assign Bus |
因此,如果timeDurations
在assignedBus
中包含匹配的数据,则该按钮必须为View Bus
,否则为Assign Bus
这是我的小提琴 - &gt; https://jsfiddle.net/943bx5px/31/
请帮忙。感谢
答案 0 :(得分:1)
问题是由for循环中的for循环引起的。检查我的solution:
hasAssignedBus(duration) {
for (var i = 0; i < this.assignedBus.length; i++) {
if(this.assignedBus[i].duration == duration) {
return true;
}
}
return false;
}
欢呼声
答案 1 :(得分:0)
您可以稍微简化数据结构。我建议你采用这种方法:
timeDurations: [
'02:30 AM - 03:00 AM',
'03:00 AM - 03:30 AM',
'03:30 AM - 04:00 AM',
'04:00 AM - 04:30 AM',
'04:30 AM - 05:00 AM',
'05:00 AM - 05:30 AM',
'05:30 AM - 06:00 AM'
],
assignedBus: {
'03:00 AM - 03:30 AM': 'Bus1',
'04:00 AM - 04:30 AM': 'Bus1',
'05:00 AM - 05:30 AM': 'Bus1'
}
然后您的标记也可以简化:
<template v-for="time in timeDurations">
<tr>
<td>{{time}}</td>
<td>
<button class="btn btn-primary">
{{ assignedBus[time] ? "View Bus" : "Assign Bus" }}
</button>
</td>
</tr>
</template>
如果您想使用您的格式,请使用:
methods: {
checkBus(duration) {
return this.assignedBus.find(function(info) {
return info.duration === duration
});
}
}
模板:
<template v-for="time in timeDurations">
<tr v-if="hasAssignedBus(time.duration)">
<td>{{time.duration}}</td>
<td><button class="btn btn-primary">
View Bus
</button></td>
</tr>
<tr v-else>
<td>{{time.duration}}</td>
<td><button class="btn btn-primary">
Assign Bus
</button></td>
</tr>
</template>