Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
886 views
in Technique[技术] by (71.8m points)

vue.js - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...