Javascript 如何检测购物车项目是否存在并添加新产品,而不更改之前的产品,而是添加新的购物车项目
如何将产品添加到购物车项目中但如果购物车项目存在则只需将产品添加到新对象中,但之前不更改对象 这是我的方法addToCart()Javascript 如何检测购物车项目是否存在并添加新产品,而不更改之前的产品,而是添加新的购物车项目,javascript,json,vue.js,Javascript,Json,Vue.js,如何将产品添加到购物车项目中但如果购物车项目存在则只需将产品添加到新对象中,但之前不更改对象 这是我的方法addToCart() 是否有解决问题的最佳方法?无论内容如何,每次调用函数时都会重置购物车项目。通过删除代码更改功能,并更改if语句: addToCart() { if (!this.products.cart_items) { this.products.cart_items = []; } const date = (new Date()).toString()
是否有解决问题的最佳方法?无论内容如何,每次调用函数时都会重置
购物车项目。通过删除代码更改功能,并更改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));
}
还是一样,结果还是和以前一样:(
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));
}
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));
}