在一个简单的VueJs应用程序中,我有多个input
元素。但是我没有和形成元素。现在,我想一次获取所有输入值并发送到服务器端[laravel]进行处理吗?
<div>
<input v-model="foo-bar" placeholder="edit me">
<input v-model="bar-foo" placeholder="edit me">
<input v-model="foo-foo" placeholder="edit me">
<input v-model="bar-bar" placeholder="edit me">
</div>
<div>
<input type="button" @click="getAllData">Send</input>
</div>
getAllData(){
// I have no idea how to get all at once!
}
答案 0 :(得分:1)
如何将所有内容存储在方便的 form 对象中,例如
new Vue({
el: '#app',
data: {
form: {} // create an object to hold all form values
},
methods: {
getAllData() {
console.info(this.form)
// axios.post('/some/url', this.form)
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
<div>
<input v-model="form['foo-bar']" placeholder="edit me">
<input v-model="form['bar-foo']" placeholder="edit me">
<input v-model="form['foo-foo']" placeholder="edit me">
<input v-model="form['bar-bar']" placeholder="edit me">
</div>
<div>
<button type="button" @click="getAllData">Send</button>
</div>
</div>
如您在演示中所见,您需要做的就是为所有值引用this.form
。
答案 1 :(得分: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 :(得分:0)
绑定到Vues data
选项的输入:
new Vue({
el: "#app",
data: {
myArray: [null, null, null, null]
},
methods: {
getAllData() {
console.log(this.myArray)
// send to server
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>
<input v-for="(arr, index) in myArray" v-model="myArray[index]" @key="index" placeholder="edit me">
</div>
<div>
<button type="button" @click="getAllData">Send</button>
</div>
</div>