How to post array of data to the server in your Vue app

May 28, 2020

When you develop the Vue application you will have to post array of data to the REST API URL given to you.

Suppose you are going to make a invoice with several products as shown in the following HTML code and you want to post the request with this array of data via Axio

Vue post array of data
<thead>
<tr>
    <th>Product Name</th>
    <th>Ordered Qty</th>
    <th>Received Qty</th>
    <th>Qty to Receive</th>
</tr>
</thead>
<tbody>
<tr>
    <td>{{ product.name }}</td>
    <td>{{ product.qty }}</td>
    <td>{{ products[index].received_qty}}</td>
    <td><input :id="product.id" v-model='products[index].qty_to_receive' /></td>
</tr>
</tbody>
</table>

Now we will see how to submit this data table to the Server I have update_products function inside the methods section of the Vue instance as shown in the below. What I am doing here is that, I will create the payload object array and place the products object inside of the payload and then payload is passed to the Post method of the Axios as the second parameter.

methods:{
    update_products: function(){
      let self = this;
      let payload = {
           products:this.products,
           id:this.purchaseorder.id,
       };
      axios.post('/api/purchaseorders/update_products', payload)
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });

    }
}