Getting form data on submit?

2019-02-06 15:18发布

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?

标签: vue.js vuejs2
3条回答
我只想做你的唯一
2楼-- · 2019-02-06 15:42

You have to define a model for your input.
<input type="text" id="name" v-model="name">

Then you you can access the value with this.name inside your getFormValues method.

This is at least how they do it in the official TodoMVC example: https://vuejs.org/v2/examples/todomvc.html (See v-model="newTodo" in HTML and addTodo() in JS)

查看更多
闹够了就滚
3楼-- · 2019-02-06 15:47

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.

查看更多
做自己的国王
4楼-- · 2019-02-06 16:01

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"

查看更多
登录 后发表回答