[英]Apply class conditionally to specific item in a list Vue.js 3.0
[英]Vue.js, conditionally adding item to an array
我有一個硬編碼的菜單項,我在其中循環以在表格中顯示其內容,然后每個項目都有一個添加按鈕。 我想要做的是允許用戶將所選項目添加到他的購物車中,我在我的數據函數中將其初始化為一個空數組,所以首先我想驗證所選項目在用戶購物車中不存在,所以如果它不存在,它將被添加,如果存在,我想將其數量增加一。 請在根 app.vue 組件的此代碼和框中找到我的代碼來實現此功能,如果需要,請在下面的評論中要求進一步說明。 謝謝
問題出在 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')
}
}
如果當前迭代比薩不等於 selectedPizza,則您在 forEach 中多次將比薩添加到購物車中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.