To add items to an array in a Vue 3 cart without generating duplicates, you can follow the following steps:
Create an empty array to store the items in the cart, e.g:
const cartItems = [];
Create a method that takes the item that needs to be added to the cart as an argument, e.g:
addToCart(item) {
// do something
}
Check if the item already exists in the cart using the Array.prototype.some()
method. This method returns true
if at least one element in the array satisfies the condition, e.g:
if (cartItems.some(cartItem => cartItem.id === item.id)) {
// item already exists in the cart, do nothing
return;
}
If the item doesn't exist in the cart, push the item to the array using the Array.prototype.push()
method, e.g:
cartItems.push(item);
You can then use the v-for
directive in the template to loop through the items in the cart array and display them.
Here's the complete code example:
<template>
<div>
<button @click="addToCart({ id: 1, name: 'Product A', price: 10 })">Add to cart</button>
<ul>
<li v-for="(item, index) in cartItems" :key="index">
{{ item.name }} - {{ item.price }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
cartItems: [],
};
},
methods: {
addToCart(item) {
if (this.cartItems.some(cartItem => cartItem.id === item.id)) {
// item already exists in the cart, do nothing
return;
}
this.cartItems.push(item);
},
},
};
</script>
Asked: 2023-07-07 00:17:32 +0000
Seen: 10 times
Last updated: Jul 07 '23