Search code examples
vue.jsv-forvue-data

How to change input value for individual object in an array using v-for in Vue?


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--;
    },
   }

Solution

  • 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>