【问题标题】:Axios post entire from. (Vue.js)axios 帖子全部来自。 (Vue.js)
【发布时间】:2017-11-29 06:19:29
【问题描述】:

有没有办法只发布整个表单,而不必指定字段?我以为我在哪里见过它,但现在找不到了。

在 JQuery 中有点像这样:

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

这是在 Vue.js 组件中。

米克

【问题讨论】:

    标签: vue.js axios


    【解决方案1】:
    <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>
    

    【讨论】:

      【解决方案2】:

      一种可能的解决方案是将v-model 与@MU 提到的对象一起使用。

      除了v-model,您还可以使用本机FormData 对象,例如当您有动态创建的输入并且您不能/不想使用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>

      【讨论】:

        【解决方案3】:
        1. 如果您使用的是 VueJS,您应该对所有表单字段使用 v-model。 https://vuejs.org/v2/guide/forms.html
        2. 在您的data() 对象中创建名为form 或类似的对象并使用v-model='form.fieldName'
        3. 使用this.axios.post('url', this.form).then(... 以 JSON 格式一起发布

        【讨论】:

          猜你喜欢
          • 2018-07-19
          • 1970-01-01
          • 2019-03-04
          • 1970-01-01
          • 1970-01-01
          • 2019-03-11
          • 2017-02-13
          • 1970-01-01
          • 2020-08-27
          相关资源
          最近更新 更多