axios 帖子全部来自.(Vue.js) [英] Axios post entire from. (Vue.js)
本文介绍了axios 帖子全部来自.(Vue.js)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法只发布整个表单,而不必指定字段?我以为我在哪里见过它,但现在找不到了.
在 JQuery 中有点像这样:
$.ajax({数据:$("form").serialize(),//等等.});
这是在 Vue.js 组件中.
米克
解决方案
一种可能的解决方案是使用 v-model
和 @MU.
除了v-model
,你还可以使用原生的FormData 对象,例如当您动态创建输入并且您不能/不想使用 v-model
绑定这些输入时:
new Vue({el: '#app',方法: {提交:函数(){const formData = new FormData(this.$refs['form']);//引用表单元素常量数据 = {};//使用前需要转换,不与 XMLHttpRequest 一起使用for (let [key, val] of formData.entries()) {Object.assign(data, { [key]: val })}控制台日志(数据);axios.post('https://jsonplaceholder.typicode.com/posts', 数据).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="应用程序"><form ref="form" @submit.prevent="提交"><input type="text" name="name"><input type="number" name="age"><button type="submit">提交</button></表单>
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
解决方案
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>
这篇关于axios 帖子全部来自.(Vue.js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文