[英]Vue.js, conditionally adding item to an array
I have a hardcoded menu Items in which I loop through to display its content in a table, then I have an add button for each item.我有一个硬编码的菜单项,我在其中循环以在表格中显示其内容,然后每个项目都有一个添加按钮。 what I want to do is to allow the user to add the selected item to his shopping cart which I initialize in my data function as an empty array, so first I want to validate that the selected Item doesn't exist in the user shopping cart, so if it doesn't exist, it will be added, if it does, I want to increase its quantity by one.
我想要做的是允许用户将所选项目添加到他的购物车中,我在我的数据函数中将其初始化为一个空数组,所以首先我想验证所选项目在用户购物车中不存在,所以如果它不存在,它将被添加,如果存在,我想将其数量增加一。 please find my code to implement this functionality in this codesandbox in the root app.vue component, Please ask for any further clarification in a comment below - if needed.
请在根 app.vue 组件的此代码和框中找到我的代码来实现此功能,如果需要,请在下面的评论中要求进一步说明。 thanks
谢谢
Problem is in the forEach inside addItem function.Please find the updated code.问题出在 addItem 函数中的 forEach 中。请找到更新的代码。
addItem(pizza, options) {
let selectedPizza = {
name: pizza.name,
siza: options.size,
price: options.price,
quantity: 1,
id: options.size === 'L' ? pizza.id.split('').reverse().join('') : pizza.id
}
if(this.cart.length > 0) {
let exist = false;
for(let index = 0; index < this.cart.length; index++) {
let item = this.cart[index];
if(item.id === selectedPizza.id && item.size === selectedPizza.size){
item.quantity++;
this.response ='Item already exist in the cart';
exist = true;
break;
}
}
if(!exist) {
this.response = ''
this.cart.push(selectedPizza)
}
} else {
this.cart.push(selectedPizza)
console.log('item is added to an empty cart')
}
}
You were adding pizzas into the cart multiple number of times inside forEach, if current iteration pizza is not equal to the selectedPizza.如果当前迭代比萨不等于 selectedPizza,则您在 forEach 中多次将比萨添加到购物车中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.