gpt4 book ai didi

javascript - Vue js 列表中的数量计数

转载 作者:行者123 更新时间:2023-12-03 01:18:22 24 4
gpt4 key购买 nike

我有一份全局产品 list 。

<span v-for="product in products">
{{product.name}}
</span>

我还有包含产品的销售。

<div v-for="sale in sales">
<span v-for="product, key in sale.items">
{{product.name}}
</span>
</div>

这会打印出本次销售的所有附加产品的列表。

 Product #1
Product #2
Product #1
Product #3
Product #2

我想要上面的列表,显示数量,而不是重复......像这样。

 Product #1 x 2
Product #2 x 2
Product #3 x 1

所以通常在常规 javascript 中我可能会这样做。

 for(var i = 0 ; i<=products.length; i++){
var qty = 0;
for(var k =0; k<=sales.items.length; k++){
if(sales.items[k].id==products[i].id){
qty++;
}
}
if(qty!=0){
console.log(products[i].name+" x "+qty);
}
}

但是我该如何在 vue.js 中做到这一点?

我已经尝试过

<div v-for="sale in sales">
<span v-for="product in products">
<span v-for="prod in sales.items" v-if="product.id==prod.id">
{{product.name}} x {{how do I get quantity here??}}
</span>
</span>
</div>

显然这行不通,因为我需要一个在产品周围的每个循环上重置的数量变量。我怎样才能做到这一点?

最佳答案

您可以为此创建自定义方法:

 <span v-for="product in products" :key="product.id">
{{product.name}} x {{ getProductQuanlity(product.id) }}
</span>


methods: {
getProductQuanlity (productId) {
var qty = 0;
for(var k =0; k <= this.sales.items.length; k++){
if(this.sales.items[k].id == productId){
qty++;
}
}
return qty

}
}

关于javascript - Vue js 列表中的数量计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51889397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com