1

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 class="shop">
        <h1>shop</h1>
        <div class="products" v-for="item in items" :key="item.id">{{ item.name }}</div>
        <button @click="addToCart">Add to Cart</button>
    </div>
    <div class="cart">
        <h1>cart</h1>
        <div class="cartitems" 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
  }
]

1 Answer 1

1
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 class="products" v-for="item in items" :key="item.id">   
        {{ item.name }}
        <button @click="addToCart(item.id)">Add to Cart</button>
     </div>
Sign up to request clarification or add additional context in comments.

6 Comments

it does not work. im getting: shop.vue:9 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'id')
@kikidoyouloveme Interesting :). item.name gets displayed? This should not be an issue, but try also @click="() => addToCart(item.id)"
Just realized your button is placed outside the v-for loop. My bad. I updated my answer
still not working. same error...
ok so after your update i think is working but i have 2 buttons of addtocart and how can i get those items after i added them to the cart in the cart?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.