Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To add items to an array in a Vue 3 cart without generating duplicates, you can follow the following steps:

  1. Create an empty array to store the items in the cart, e.g:

    const cartItems = [];
    
  2. Create a method that takes the item that needs to be added to the cart as an argument, e.g:

    addToCart(item) {
      // do something
    }
    
  3. 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;
    }
    
  4. 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);
    
  5. 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>