vue.js - 如何根据两个数组的比较进行过滤?
问题描述
所以,我有两个数组。一个包含一些约会,这些约会都说明了他们被安排在哪一天。在另一个数组中,我有所有工作日的名称。我只想打印有约会的工作日。
<b-col class="h-100">
<b-row v-for="day in week" class="schemaLine">
<div>{{day}}</div>
<b-row v-for="appointment in appointments" class="">
<div v-if="appointment.day === day && companies.includes(appointment.company)">
<b-button class="appointmentBlock w-100 m-2">
<div class="appointmentTitle">
{{appointment.name}}
</div>
<div class="appointmentTime">
{{appointment.time}}
</div>
</b-button>
</div>
</b-row>
</b-row>
</b-col>
解决方案
仅打印您至少有一个约会的日期的最简单方法是预处理您的约会。这还有一个额外的好处,那就是不需要您在一周中的每一天都检查每个约会。
首先,我们创建一个计算属性appointmentsPerDay
,它将一天映射到一个约会数组。然后我们创建另一个计算属性,该属性获取该对象的键并对它们进行排序,以便您可以遍历它们:
computed: {
appointmentsPerDay () {
// We assume that you get the appointments variable somehow
const appointmentsPerDay = {};
for (const appointment of this.appointments) {
const { day } = appointment;
// We initialise an array if no such array exists
if (!appointmentsPerDay[day]) {
appointmentsPerDay[day] = [];
}
// Now that it is guaranteed that we have an array, add our appointment to it
appointmentsPerDay[day].push(appointment);
}
return appointmentsPerDay;
},
visibleDays() {
const days = Object.keys(this.appointmentsPerDAy);
days.sort();
return days;
}
}
现在我们如何使用这些?
<b-col class="h-100">
<b-row v-for="day in visibleDays" class="schemaLine">
<div>{{day}}</div>
<b-row v-for="appointment in appointmentsPerDay[day]" class="">
<div v-if="companies.includes(appointment.company)">
<b-button class="appointmentBlock w-100 m-2">
<div class="appointmentTitle">
{{appointment.name}}
</div>
<div class="appointmentTime">
{{appointment.time}}
</div>
</b-button>
</div>
</b-row>
</b-row>
</b-col>
正如你所看到的,我们只需要交换一些变量。您仍然看到我们必须使用 v-if 来过滤公司。显然,我们也可以对其进行预处理以完全消除 v-if 并循环遍历我们实际想要显示的数据。我会把它留给你作为练习。
推荐阅读
- jenkins - 针对开放 PR 提交的 Jenkins web-hook 触发器
- android - Android Studio 调试器只工作一次
- c# - c#替换՛字符
- django - 如何使用 SQS 代理监控 celery 中的任务?
- node.js - NestJS REST API 因长时间运行的请求而超时
- javascript - 如何摆脱 Plotly 图表顶部的空白?
- mysql - 1292 截断不正确的 DOUBLE 值:''
- swiftui - 用动作调用 SwiftUI 按钮?
- abp - 如何在 Abp 中隐藏默认服务端点
- java - JUnit:断言集合包含具有特定属性的元素