0

I'm making a shopping cart. I want to show the price of each product based on their quantity. I made the buttons to add or subtract the quantity of products. However the quantity changes in all products because they all share the same data. How can I do to change quantity for the specific product?

    <div  v-for="(cartProduct,index) in cartProducts" :key="index" class="px-3 py-2">
        <div id="cartProducts">
            <p>{{cartProduct.description}}</p>
            <button @click="subtract" >-</button> <p>{{quantity}}</p> <button @click="add">+</button>
            <p>$ {{cartProduct.price*quantity}}</p>
        </div>  
    </div>
    export default {
     data(){
      return{
        quantity:1
       }
     },
     methods:{
        add(){
         this.quantity++;
    },
       subtract(){
        this.quantity--;
    },
   }

1 Answer 1

1

You have to do is, build an object for all products having quantity field, just like this

<template>
  <div>
    <div
      v-for="(cartProduct, index) in cartProducts"
      :key="index"
      class="px-3 py-2"
    >
      <div id="cartProducts">
        <p>{{ cartProduct.description }}</p>
        <button @click="subtractProduct(index)">-</button>
        <p>{{ cartProduct.quantity }}</p>
        <button @click="addProduct(index)">+</button>
        <p>$ {{ cartProduct.price * cartProduct.quantity }}</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cartProducts: [
        {
          description: "product 1",
          price: 100,
          quantity: 0,
        },
        {
          description: "product 2",
          price: 100,
          quantity: 0,
        },
        {
          description: "product 3",
          price: 100,
          quantity: 0,
        },
      ],
    };
  },
  methods: {
    addProduct(index) {
      this.cartProducts[index].quantity++;
    },
    subtractProduct(index) {
      if (this.cartProducts[index].quantity !== 0)
        this.cartProducts[index].quantity--;
    },
  },
};
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it helps. Also thank you for adding the if statement for the subtract method

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.