submit form in vue
<template>
<form @submit.prevent="submitForm">
<label for="name">Name:</label>
<input type="text" id="name" v-model="formData.name" required>
<label for="email">Email:</label>
<input type="email" id="email" v-model="formData.email" required>
<button type="submit">Submit</button>
</form>
</template>
<script>
export default {
data() {
return {
formData: {
name: '',
email: ''
}
};
},
methods: {
submitForm() {
// Perform form submission logic here
// Access form data using this.formData
// You can make API calls, perform validations, etc.
console.log('Form submitted with data:', this.formData);
}
}
};
</script>
Explanation:
- Template Section:
- A form element is defined with the
@submit.prevent
directive to handle form submission and prevent the default behavior (page reload). Two input fields for "Name" and "Email" are defined using
<input>
elements with respectiveid
,v-model
directives to bind data to theformData
properties, andrequired
attribute for mandatory input.Script Section:
data()
method initializes theformData
object with emptyname
andemail
properties.- The
submitForm()
method is defined to handle form submission. Currently, it logs the form data to the console. - This method can be expanded to perform various actions like making API calls, form validation, etc. using the
this.formData
object that contains the form data.
When the form is submitted, it triggers the submitForm()
method, accessing the form data stored in formData
, allowing further actions to be executed, such as data validation or sending it to a server.