当购物车中已存在ID时,Vue.js购物车数量增加

时间:2018-10-18 10:56:03

标签: javascript vue.js e-commerce

嗨,我正在创建自己的购物车,但当购物车中已有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();
    },

1 个答案:

答案 0 :(得分:1)

只需检查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();
}