Home > OS >  how to add and get items from an array in vue3?
how to add and get items from an array in vue3?

Time:01-10

so I am build a shop with a cart in it and I want to add products to the cart and view them in the cart after I added them. how can I fix my code? as I stumbled across the push method of JavaScript but for some reason it does not work for me. so, how can I add items to the cart and retrieve them later?

here is my code:

shop.vue

    <template>
    <div >
        <h1>shop</h1>
        <div  v-for="item in items" :key="item.id">{{ item.name }}</div>
        <button @click="addToCart">Add to Cart</button>
    </div>
    <div >
        <h1>cart</h1>
        <div  v-for="item in cart" :key="item.id">{{ item.name }} {{ item.price }}</div>
    </div>
</template>
<script>
import Products from "../db.json"

export default {
    name: "shop",
    data() {
        return {
            items: Products,
            cart: []
        }
    },
    methods: {
        addToCart() {
            this.cart.push(this.items.id)
        }
    }
}
</script>

db.json as my "db" with the products

[
  {
    "id": 1,
    "name": "iphone",
    "price": 2000
  },
  {
    "id": 2,
    "name": "galaxy",
    "price": 3000
  }
]

CodePudding user response:

addToCart() {
  this.cart.push(this.items.id)
}
  1. There is a typo (I assume). You want to add a certain item id to the cart. this.items is an array and does not have an id property.

  2. You actually want to pass the id as an argument to the addToCart method:

    <button @click="addToCart(item.id)">Add to Cart</button>

Then grab and add it to the cart:

    addToCart(id) {
      this.cart.push(id)
    }

Update/ Edit:

You also need to place the <button> inside the v-for loop, otherwise it will not have access to the iteration scope:

     <div  v-for="item in items" :key="item.id">   
        {{ item.name }}
        <button @click="addToCart(item.id)">Add to Cart</button>
     </div>
  • Related