Getting form data to submit?
When my form is submitted, I want to get the input value:
<input type="text" id="name"> I know that I can use form input bindings to update variable values, but how can I do this when submitting. I currently have:
<form v-on:submit.prevent="getFormValues"> But how can I get the value inside the getFormValues ββmethod?
Also, the side question is, is there any benefit to applying it, rather than updating a variable when a user enters data through a binding?
You should use model binding, especially here, as mentioned by Hlangguru in his answer.
However, there are other methods that you can use, such as regular Javascript or links. But I really donβt understand why you would like to do this instead of binding to the model, for me this does not make sense:
<div id="app"> <form> <input type="text" ref="my_input"> <button @click.prevent="getFormValues()">Get values</button> </form> Output: {{ output }} </div> As you can 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: https://jsfiddle.net/sh70oe4n/
But once again my answer is far from what you might call "good practice"
The submit form action generates a submit event, which, among other things, provides you with the purpose of the event.
The purpose of dispatching an event is an HTMLFormElement, which has the elements property. See this MDN link for how to iterate or access specific elements by name or index.
If you add a name property to the property, you can access a field like this in the form submit handler:
<form v-on: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 } } } What you want to do this: HTML forms already provide useful logic, such as disabling the submit action when the form is invalid, which I prefer not to repeat in Javascript. Therefore, if I find that I am creating a list of elements that require a small amount of input before performing an action (for example, by selecting the number of elements you want to add to the cart), I can put the form in each element, use the native form check, and then capture the value the target form included in the submit action.
You must define a model to enter.<input type="text" id="name" v-model="name">
You can then access the value using this.name inside your getFormValues method.
At least this is 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 )