Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push to array with v-model

I'm new to Vue.js, and I'm trying to create a shop app with Vue & Webpack. I have some products in a json file, and rendering them with a v-for.

When clicking on Add to cart button, it should put the product number, and the selected quantity to an array.

How can I properly increase quantity for a specific product? So far I have the following:

<template>
  <div v-for="(product, index) in products" >
    <div><img :src="product.product_image" /></div>
    <div>
      <input type="number" min="0" v-model="qty[index]" />
      <button @click="addToCart(product.id, qty[index])">Add to cart</button>
    </div>
  </div>
</template>


<script>

  import productList from '../products.json';

  export default{
    name: 'shop',
    data(){
      return {
        products: productList,
        cartElements: [],
        qty: [],
      }
    },
    props: [ 'itemsInCart' ],
    methods:{
      addToCart(product_id, quantity){
        this.cartElements.push( {
          "id" : product_id,
          "quantity" : quantity,
        } );
        console.log(this.cartElements);
      },
    },
  }
</script>

The result is ok, but the input fields are acting weird.

e.g. If I increase the third product's input, it sets the first and second product input to 1, and only then sets the third input to the desired number.

like image 564
renataedit Avatar asked Jun 05 '26 12:06

renataedit


1 Answers

You are expecting qty = [] to be automatically populated by the v-model directive. Try initializing that array yourself using vuejs' created function, like this:

<template>
<div v-for="(product, index) in products" >
    <div><img :src="product.product_image" /></div>
    <div>
        <input type="number" min="0" v-model="qty[index]" />
        <button @click="addToCart(product.id, qty[index])">Add to cart</button>
    </div>
</div>
</template>
    
    
<script>
import productList from '../products.json';
export default{
    name: 'shop',
    data(){
        return {
            products: productList,
            cartElements: [],
            qty: [],
        }
    },
    props: [ 'itemsInCart' ],
    methods:{
        addToCart(product_id, quantity){
            this.cartElements.push( {
                id" : product_id,
                quantity" : quantity,
            });
            console.log(this.cartElements);
        },
    },
    created: function () {
        var i = 0;
        for (i = 0; i < this.products.length; i++){
            this.$set(this.qty, i , 0) // This is the vuejs-way of setting array values
        }
    }
}
</script>
like image 180
andresgottlieb Avatar answered Jun 08 '26 17:06

andresgottlieb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!