Getting form data on submit?

You should use model binding, especially here as mentioned by Schlangguru in his response.

However, there are other techniques that you can use, like normal Javascript or references. But I really don't see why you would want to do that instead of model binding, it makes no sense to me:

<div id="app">
  <form>
    <input type="text" ref="my_input">
    <button @click.prevent="getFormValues()">Get values</button>
  </form>
  Output: {{ output }}
</div>

As you see, I put ref="my_input" to get the input DOM element:

new Vue({
  el: '#app',
  data: {
    output: ''
  },
  methods: {
    getFormValues () {
      this.output = this.$refs.my_input.value
    }
  }
})

I made a small jsFiddle if you want to try it out: https://jsfiddle.net/sh70oe4n/

But once again, my response is far from something you could call "good practice"


The form submit action emits a submit event, which provides you with the event target, among other things.

The submit event's target is an HTMLFormElement, which has an elements property. See this MDN link for how to iterate over, or access specific elements by name or index.

If you add a name property to your input, you can access the field like this in your form submit handler:

<form @submit.prevent="getFormValues">
  <input type="text" name="name">
</form>

new Vue({
  el: '#app',
  data: {
    name: ''
  },
  methods: {
    getFormValues (submitEvent) {
      this.name = submitEvent.target.elements.name.value
    }
  }
}

As to why you'd want to do this: HTML forms already provide helpful logic like disabling the submit action when a form is not valid, which I prefer not to re-implement in Javascript. So, if I find myself generating a list of items that require a small amount of input before performing an action (like selecting the number of items you'd like to add to a cart), I can put a form in each item, use the native form validation, and then grab the value off of the target form coming in from the submit action.

Tags:

Vue.Js

Vuejs2