首页 > 解决方案 > 如何检测cart_items是否存在并添加新产品而不更改之前的产品但在cart_items中添加新产品

问题描述

我如何将产品添加到cart_items但是如果cart_items 存在它只是将产品添加到新对象而不是之前更改对象

    "cart": {
        "cart_items": [
          {
            "product": {
              "name": "Salad Buah",
              "price": "15900",
              "stock": "6",
              "image": "https://firebasestorage.googleapis.com/v0/b/francise-fb70a.appspot.com/o/salad-buah-3.jpg?alt=media&token=ccb9e91b-c809-4cbe-bdc2-96f7835d8201",
              "promo": {
                "name": "Mukbang Online",
                "type": "discount",
                "amount": "100",
                "from": "2020-10-25",
                "to": "2020-10-26",
                "desc": "Makan Kenyang",
                "id": 2
              },
              "id": 5
            },
            "qty": 4
          }
        ]
    }

这是我的方法 addToCart()

addToCart() {
            if (this.products.cart_items) {
                this.products.cart_items.push([...{product: {...this.product, promo: this.promo_id}, qty: this.qty}])
            }

            const date = (new Date()).toString().split(' ').splice(1,4).join(' ')

            this.products.cart_items = [];
            this.products.store = [];
            this.products.cart_items.push({product: {...this.product, promo: this.promo_id}, qty: this.qty})
            this.products.store.push({...this.partner, store_promo: this.promo_partner})
            this.products.date_order = date;

            console.log(this.cart_items)

            axios
                .post("http://localhost:3000/cart/", this.products)
                .then(() => {
                    swal("Belanja Berhasil!", {
                        icon: "success",
                    });
                })
                .catch((error) => console.log(error));
        }

有没有解决问题的最佳方法?

标签: javascriptjsonvue.js

解决方案


cart_items无论内容如何,​​每次调用该函数时都会重置。通过删除代码更改函数并更改if语句:

addToCart() {

  if (!this.products.cart_items) {
    this.products.cart_items = [];
  }

  const date = (new Date()).toString().split(' ').splice(1, 4).join(' ')

  this.products.store = [];
  this.products.cart_items.push({
    product: { ...this.product,
      promo: this.promo_id
    },
    qty: this.qty
  })
  this.products.store.push({ ...this.partner,
    store_promo: this.promo_partner
  })
  this.products.date_order = date;

  console.log(this.cart_items)

  axios
    .post("http://localhost:3000/cart/", this.products)
    .then(() => {
      swal("Belanja Berhasil!", {
        icon: "success",
      });
    })
    .catch((error) => console.log(error));
}

推荐阅读