I would like to add my object from my item array, only once to my cart. Right now you can add the same object several times. I have my array in a index.js file and my data comes from store (index.js). The language Im working with is Vue3 with router.
<div v-if="product" class="product-details">
<h3 class="text-center">{{ product.name}}</h3>
<p class="description">{{ product.description }}</p>
<img :src ="` ${ product.img }`"/>
<h3 class="text-center">{{ product.price.toFixed(2)}} Euro</h3>
<div class="cart-total" v-if="product_total">
<h3>In Cart</h3>
<h4>{{ product_total}}</h4>
</div>
<div class="button-container">
<button class="add" @click="addToCart()"> Add</button>
</div>
</div>
</div>
</template>
<script>
export default{
data(){
return{
}
},
props:['product', 'active'],
methods: {
addToCart() {
this.$store.commit('addToCart', this.product)
}
},
computed: {
product_total(){
return this.$store.getters.productQuantity(this.product)
}
}
}
mutations: {
addToCart(state, product) {
let item = state.cart.find(i => i.id === product.id)
if (item){
item.quantity++
} else {
state.cart.push({...product, quantity: 1})
}
updateLocalStorage(state.cart)
},
Don't add quantity like that. because if you add extra quantity than, vue js that propery is not reacted by default. so we have to tell vue , for reactivity, so vue can make getter and setter for that object.
mutations: {
addToCart(state, product) {
...
if (item){
item.quantity++
} else {
Vue.set(item,'quantity',1) // now vue will add getters and setters for this key quantity . now quantity change will automatically reflect.
}
...
},
you can refer to this wonderful article. https://medium.com/js-dojo/reactivity-in-vue-js-and-its-pitfalls-de07a29c9407