Luka
Luka

Reputation: 758

How to set up a dynamic created input field (array) with a default value in Vue.js

I am trying to create a form which shows me rows of products coming through axio. Each row should have an input field which should have a 0 as a default value and then I want a + and - to increase the figure. In the end I want to be able to send the form off with the individual values for each product.

Below is my first attempt. I get the rows with the products, but the default value in the input field for the qty is empty and not 0 as it should be. so it does not seem to take the 0 which I set in data. I have tried to set it in Axio as well like this.products.qty = 0; but that does not work as well. How can I achieve it?

 <template>
<div>
 <table class="table">
  <tr>
    <th>Product Name</th>
    <th>Quantity</th>
  </tr>
    <tr v-for="(product, index) in products" :key='product.productId' >
    <td>{{ product.productName }}
      <input type="text" name="product.productId" :value="product.productId" />
    </td>
    <td>
      <div class="minusplusnumber">
        <div class="mpbtn minus" v-on:click="mpminus(index)">
          -
        </div>
        <div id="field_container">
          <input type="number" name="product.qty" :value="product.qty" disabled />
        </div>
        <div class="mpbtn plus" v-on:click="mpplus(index)">
          +
        </div>
      </div>
    </td>
  </tr>
  </table>
export default {
  name: "example",

  data: () => ({
     products:[{
                "productId": '',
                "productName" : '',
                "qty" : 0,
                }],
  }),

  methods: {
                    
     loadProducts : function () {

         axios
             .post('/products/get-all-products')
             .then(res => {
                   this.products = res.data.products;
                   // tried below also not working
                   this.products.qty = 0
              })
              .catch(err => {
                  console.log(err);
              });
     }

      mpplus: function (index) {
           this.newQty =   this.products[index].qty+1;
           Vue.set( this.products[index].qty, index, this.newQty)
      }

      mpminus: function (index) {
           this.newQty =   this.products[index].qty-1;
           Vue.set( this.products[index].qty, index, this.newQty)
      }

     }
   }
};

Upvotes: 0

Views: 339

Answers (1)

mare96
mare96

Reputation: 3859

You need something like this in your :

axios.post('/products/get-all-products')
.then(res => {
    res.data.products.forEach(prod => {
        this.products.push({
            "productId": prod.productId,
            "productName" : prod.productName,
            "qty" : 0,
        }) 
    })
})

With that code above you will map data from your response with the new field qty.

I guess that is what you need.

Upvotes: 1

Related Questions