Get all Input values - Vuejs

一笑奈何 提交于 2020-01-23 17:08:09

问题


I have multiple input elements in a simple VueJs application. But I don't have and form elements. Now I want to get all the input values at once and send to server-side [laravel] for processing?

<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!
}

回答1:


How about you store everything in a convenient form object, eg

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>

As you can see in the demo, all you need to do is reference this.form for all the values.




回答2:


Bind the inputs to Vues data option:

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>


来源:https://stackoverflow.com/questions/54885894/get-all-input-values-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!