Vue-基于数组的父V-获取当前索引/数组计数



我有两个嵌套的v-for元素,看起来像:

<div class="category" v-for="(category, categoryIndex) in categories">
<div class="product" v-for"(product, productIndex) in cateogry)">
{{product.name}}
</div>
</div>

我只想展示前五种产品,而不考虑类别的数量和每个类别中的产品数量。

如何获取第二个v-for元素内部的累积索引计数(相对于categoryIndex父数组中显示的产品总数(?

如果我理解了,它将类似于这个

<div class="category" v-for="(category, categoryIndex) in categories">
{{ category.name }}
<div class="product" v-for="(product, productIndex) in category.products.slice(0, nbProductToShow)">
{{(categoryIndex*nbProductToShow)+(productIndex+1)}}
{{product.name}}
</div>
</div>

Vue

new Vue({
data : {
nbProductToShow : 5,
categories : [{
id : 3445,
name : 'shoes',
products : [
{ id: 23234, name : 'Pink unicorn shoes'}, 
// ...
]
},{
id : 3447,
name : 'hat',
products : [
{ id: 232, name : 'Pink long hat with unicorn'}, 
// ...
]
}
]
}
})

您可以通过将产品id传递给函数并根据其返回值显示产品来检查产品是否在前五个呈现的产品中。这里有一个例子:

<template>
<div>
<div class="category" v-for="(category, categoryIndex) in categories" :key="categoryIndex">
<div class="product" v-for="(product, productIndex) in category.products" :key="productIndex">
<span v-if="incrementCount(product.id)">{{product.name}}</span>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
categories: [
{
products: [
{ id: 1, name: "1" },
{ id: 2, name: "2" },
{ id: 3, name: "3" },
]
},
{
products: [
{ id: 4, name: "4" },
{ id: 5, name: "5" },
{ id: 6, name: "6" },
]
}
]
};
},
methods: {
incrementCount: function(id) {
let count = 0;
for(let i = 0; i < this.categories.length; i++)
for(let j = 0; j < this.categories[i].products.length; j++)
if(count++ < 5 && this.categories[i].products[j].id===id)
return true;
return false;
}
},
};
</script>

相应地,输出为:

1
2
3
4
5

最新更新