I created a form with various input fields and upon submission, I am displaying the data in a modal. Although it functions correctly, I have concerns regarding the cleanliness of my code.
Below is the simplified HTML structure:
<div id="app">
<form @submit.prevent="getValues">
<label>Last Name: </label><input type="text" name="lastName">
<br>
<button>Submit</button>
</form>
</div>
The Vue instance and getValues function are as follows:
let app = new Vue({
el: '#app',
data:{
lastName: ''
},
methods:{
getValues(submitEvent){
this.lastName = submitEvent.target.elements.lastName.value
}
}
})
To simplify the code, I decided to implement v-model:
Modified HTML:
<div id="app">
<form @submit.prevent="getValues">
<label>First Name: </label><input type="text" v-model="firstName">
<button>Submit</button>
</form>
</div>
Updated Vue section:
let app = new Vue({
el: '#app',
data:{
firstName: ''
},
methods:{
getValues(submitEvent){
firstName = this.firstName
}
}
})
Although the implementation works, I find firstName = this.firstName
confusing. Changing the variable names did not yield the desired results. Is the variable "firstName" inside getValues actually utilized, or is the value rendered due to two-way binding using v-model (which may be challenging to ascertain since the modal only appears after form submission)?
Here's a JSFiddle showcasing both approaches.
Which approach is more appropriate? Can they be used interchangeably? What sets them apart?