简体   繁体   中英

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. thanks

Problem is in the forEach inside addItem function.Please find the updated code.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM