Search code examples
vue.jsvuejs2

Getting form data on submit?


When my form is submitted I wish to get an input value:

<input type="text" id="name">

I know I can use form input bindings to update the values to a variable, but how can I just do this on submit. I currently have:

<form v-on:submit.prevent="getFormValues">

But how can I get the value inside of the getFormValues method?

Also, side question, is there any benefit to doing it on submit rather than updating variable when user enters the data via binding?


Solution

  • 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"