How does the product object look - is there a unique ID?
Sep 1, 2022
15
Level 7
toggle item in an array
At the moment, when I click on a product, it adds to the array selectedItems and adds onto the totalPrice, I would like to remove from the array selectedItems and minus the price form totalPrice if it's in the array?! please help...
addProduct(product) {
this.selectedItems.push(product);
console.log("Product: ", product);
this.totalPrice += product.price;
},
Level 104
@boyjarv okay, you're using Vue's options API, so still it should be computed, just different syntax - moving totalPrice from data into computed:
data() {
return {
selectedItems: [],
itemSelected: false,
};
},
computed: {
totalPrice() {
return this.selectedItems.reduce((total, product) => total += product.price, 0)
}
}
Aside, since addProduct should toggle the selection; I would modify the earlier suggestion:
function addProduct(product) {
var index = selectedItems.findIndex(item => item.id === product.id);
if (index === -1) {
selectedItems.push(product);
} else {
selectedItems.splice(index, 1);
}
}
1 like
Please or to participate in this conversation.