我如何将产品添加到 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));
}
是否有解决问题的最佳方法?
答案 0 :(得分:0)
每次调用该函数时,无论其内容如何,都将重置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));
}