javascript - 如何检测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));
}
有没有解决问题的最佳方法?
解决方案
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));
}
推荐阅读
- google-cloud-platform - 使用 gcloud beta 构建触发器 create cloud-source-repositories 不适用于 --dockerfile-image
- python-3.7 - 使用模糊搜索提取匹配
- database - Heroku Postgres:psycopg2.ProgrammingError:没有要获取的结果
- python - 以熊猫中其他两列为条件替换一列的值
- python - 在产品名称前添加一个字符串
- python - 如何让不同的文件运行 python 代码
- python - 为什么 python 允许切片超过列表的长度?
- node.js - 在构造函数之前调用 Typescript/javascript 方法
- common-lisp - 在 Common Lisp 中使用标签与 helper-and-main 与嵌套 defun 之间的比较。哪个是最好的?
- javascript - 引导表打印不适用于 showColumnsSearch