繁体   English   中英

Vue.js,有条件地将项目添加到数组

[英]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.

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