Vue.js 当 id 已经存在于购物车中时,购物车数量增加
Vue.js cart quantity increment when id is already existing in cart
您好,我正在创建自己的购物车,但每当 ID 已经在购物车中时,我遇到了数量增加的问题,所以我的问题是如何在 cartList 中过滤 ID?所以 id 不会重复,而是增加购物车中过滤后的 id。
cartList: [],
productList:[],
cartadd: {
id: 0,
name: 0,
price: 0,
quantity: 0,
image: ''
}
viewStorageCart () {
if(localStorage.getItem('cartStorageList')) {
this.cartList = JSON.parse(localStorage.getItem('cartStorageList'))
}
},
addStorageCart (product) {
this.cartadd.id = product.id;
this.cartadd.name = product.product_name;
this.cartadd.price = product.product_price;
this.cartadd.quantity = 1;
this.cartadd.image = product.product_image;
this.cartList.push(this.cartadd);
this.cartadd = {}
this.storeCart();
},
removeStorageCart (product) {
this.cartList.splice(product, 1);
this.storeCart();
},
storeCart() {
let parsed = JSON.stringify(this.cartList);
localStorage.setItem('cartLicartStorageListst', parsed)
this.viewStorageCart();
},
只需检查 cartList 数组并增加数量(如果存在)
addStorageCart (product) {
var findProduct = this.cartList.find(o => o.id === product.id)
if(findProduct){
findProduct.quantity +=1;
return;
}
this.cartadd.id = product.id;
this.cartadd.name = product.product_name;
this.cartadd.price = product.product_price;
this.cartadd.quantity = 1;
this.cartadd.image = product.product_image;
this.cartList.push(this.cartadd);
this.cartadd = {}
this.storeCart();
}
您好,我正在创建自己的购物车,但每当 ID 已经在购物车中时,我遇到了数量增加的问题,所以我的问题是如何在 cartList 中过滤 ID?所以 id 不会重复,而是增加购物车中过滤后的 id。
cartList: [],
productList:[],
cartadd: {
id: 0,
name: 0,
price: 0,
quantity: 0,
image: ''
}
viewStorageCart () {
if(localStorage.getItem('cartStorageList')) {
this.cartList = JSON.parse(localStorage.getItem('cartStorageList'))
}
},
addStorageCart (product) {
this.cartadd.id = product.id;
this.cartadd.name = product.product_name;
this.cartadd.price = product.product_price;
this.cartadd.quantity = 1;
this.cartadd.image = product.product_image;
this.cartList.push(this.cartadd);
this.cartadd = {}
this.storeCart();
},
removeStorageCart (product) {
this.cartList.splice(product, 1);
this.storeCart();
},
storeCart() {
let parsed = JSON.stringify(this.cartList);
localStorage.setItem('cartLicartStorageListst', parsed)
this.viewStorageCart();
},
只需检查 cartList 数组并增加数量(如果存在)
addStorageCart (product) {
var findProduct = this.cartList.find(o => o.id === product.id)
if(findProduct){
findProduct.quantity +=1;
return;
}
this.cartadd.id = product.id;
this.cartadd.name = product.product_name;
this.cartadd.price = product.product_price;
this.cartadd.quantity = 1;
this.cartadd.image = product.product_image;
this.cartList.push(this.cartadd);
this.cartadd = {}
this.storeCart();
}