I have an array of data called products and I'm passing it to my component in props, then using v-for order in orders to display it inside that component, when I click on a button, it takes that order and push it inside another array called orders; now I want to be able to push it only if it wasn't pushed before other wise just increment the quantity.
Here's my code:
<template>
<div v-for="product in products">{{ product.name }}</div>
</template>
What I want, say is if product.id = order.id don't push other quantity++;
props: {
products: Array,
orders: Array,
}
methods: {
for(let i=0; i<this.orders.length; i++){
if(product.id != this.orders[i].id || this.orders.length == 0){
console.log('sure what the hell');
console.log(this.orders[i].id);
this.orders.push(product);
} else {
console.log('baught it before');
console.log(this.orders[i].id);
}
}
I try it but it keeps giving me undefined.
I think it is working but it needs an initial push because it keeps saying the length of orders is zero so nothing is pushed, when I enable a push outside of the if statement it doubles the pushes
You shouldn't change something that was passed in as a prop
(read up on "one way flow").
Either have your orders
array as a local data object in the current component or $emit
an addToCart
event from this component and handle the actual adding to cart in the parent by listening to this event.
Assuming your orders
are in the local data object:
data() {
return {
orders: [
{ id: 'exists', quantity: 1 }
]
}
},
methods: {
addToCart(product) {
let exists = this.orders.find(p => p.id == product.id)
if(exists == -1) { // doesn't exists yet
this.orders.push(product)
} else {
this.orders[exists].quantity++
}
}
}