Mick
Mick

Reputation: 1561

Axios post entire from. (Vue.js)

Is there a way to just post the entire form, instead of having to specify the fields? I thought I had seen it somewhere but can't find it now.

A bit like this in JQuery:

$.ajax({
    data: $("form").serialize(),
    //etc.
});

This is in Vue.js component.

Mick

Upvotes: 6

Views: 11906

Answers (3)

Marek Urbanowicz
Marek Urbanowicz

Reputation: 13634

  1. If you are using VueJS you should use v-model for all form fields. https://v2.vuejs.org/v2/guide/forms.html
  2. Create in your data() object called form or something similar and use v-model='form.fieldName'
  3. Post all together as JSON with this.axios.post('url', this.form).then(...

Upvotes: 4

Rahman Rezaee
Rahman Rezaee

Reputation: 2165

<form v-on:submit.prevent="getAllData" id="frm">    
      <input name="input1" placeholder="edit me">
      <input name="input2" placeholder="edit me">
      <input name="input3" placeholder="edit me">
      <input name="input4" placeholder="edit me">
      <input type="submit" >Send</input>
</form>


<script>
   ....
   //your method parts
   methods:{
      getAllData(){
      
         let myForm = document.getElementById('frm'); 
         let formData = new FormData(myForm);
         const data = {}; 
         // need to convert it before using not with XMLHttpRequest
         for (let [key, val] of formData.entries()) {
               Object.assign(data, {[key]: val})
         }
         console.log(data);
       },
    }
   ....
<script>

Upvotes: 0

Egor Stambakio
Egor Stambakio

Reputation: 18126

One possible solution is to use v-model with object as mentioned by @MU.

Apart from v-model, you can also use native FormData object, for example when you have dinamically created inputs and you can't/don't want to bind these inputs using v-model:

new Vue({
  el: '#app',
  methods: {
    submit: function () {
      const formData = new FormData(this.$refs['form']); // reference to form element
      const data = {}; // need to convert it before using not with XMLHttpRequest
      for (let [key, val] of formData.entries()) {
        Object.assign(data, { [key]: val })
      }
      console.log(data);
      axios.post('https://jsonplaceholder.typicode.com/posts', data)
        .then(res => console.log(res.request.response))
    }
  }
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<div id="app">
  <form ref="form" @submit.prevent="submit">
    <input type="text" name="name">
    <input type="number" name="age">
    <button type="submit">Submit</button>
  </form>
</div>

Upvotes: 9

Related Questions