Axios发布整个. (Vue.js) [英] Axios post entire from. (Vue.js)

查看:54
本文介绍了Axios发布整个. (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.

在JQuery中有点像这样:

A bit like this in JQuery:

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

这在Vue.js组件中.

This is in Vue.js component.

密克

推荐答案

一种可能的解决方案是将v-model @MU .

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

除了v-model,您还可以使用本机 FormData 对象,例如当您动态创建输入并且不想/不想使用v-model绑定这些输入时:

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>

这篇关于Axios发布整个. (Vue.js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆