Currently, I am in the process of creating a prototype for an item-list and a shopping-cart. Both components function as standalone entities but are connected through a vuex-store. The item-list contains various elements that can be added to the shopping-cart with different quantities. When an item is added, it becomes an object with specific information (such as id, name, quantity) stored in an array named "products". This object is then displayed within the shopping cart. The issue arises when adding the same element to the shopping-cart with different quantities. While it is correctly added as a new item, I would like the system to update the quantity and price of the existing item rather than duplicating it. Therefore, there needs to be a check implemented to identify if the same element (based on its id) already exists in the shopping-cart and consolidate them. I hope my explanation is clear :D
The function responsible for adding elements to the array looks like this:
addToBasket(key) {
if (this.products[key].qty >= 1) {
this.$store.commit('addProduct', {
id: this.products[key].product_id,
title: this.products[key].title,
price: {
value: this.products[key].price.value,
currency: this.products[key].price.currency,
},
qty: this.products[key].qty
});
}
}
The corresponding mutation within the store is as follows:
addProduct(state, payload) {
state.products.push(payload);
}