我需要生成包含 24 列表条目的日历日概览 - 每小时 1 个。如何结合 v-for="(product, index) in products"
并检查每小时 0-23 的 product.name.startTimeHour
?
到目前为止我所拥有的:
<template v-for="(product, index) in products">
<product-item
v-if="product.name.startTimeHour === '11'"
:key="product.id"
:index="index"
:data="product"
></product-item>
<template v-else>
No entry for startTimeHour: [time]
</template>
</template>
(如果相关,我正在使用 Bento VueJS starter 模板)
最佳答案
请查看this example 。
使用的标记:
<div id="app">
<div v-for="hourNumber in 24" class="hour-entry">
<div
class="product"
v-for="(product, idx) in products"
v-if="product.startTimeHour === hourNumber"
key="product.id"
>
{{ product.name }}
</div>
<div v-if="getProductsNumPerHour(hourNumber) === 0">
No entry for startTimeHour [{{ hourNumber }}]
</div>
</div>
</div>
使用的JS:
new Vue({
el: '#app',
data: {
products: [
{
id: 1,
name: 'Product One',
startTimeHour: 4
},
{
id: 2,
name: 'Product Two',
startTimeHour: 10
},
{
id: 3,
name: 'Product Three',
startTimeHour: 15
},
{
id: 4,
name: 'Product Four',
startTimeHour: 15
},
]
},
methods: {
getProductsNumPerHour (hourNum) {
return this.products.filter(prod => {
return prod.startTimeHour === hourNum
}).length
}
}
})
在这里,我们首先迭代 24 小时数字,然后迭代每个小时数字内的所有现有产品,并仅渲染开始时间与当前时间小时数字匹配的产品。
还有辅助方法 getProductsNumPerHour()
用于检测何时没有给定小时数的产品。
我不确定您的代码product.name.startTimeHour
,看起来您的产品name属性是一个对象,但为什么不放置startTimeHour 作为单独的产品属性,如我的示例中所示。如果我遗漏了什么,请更详细地解释您的需求。
关于javascript - 生成 24 个条目的列表并检查对象中是否存在内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60616353/