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:

  1. Template Section:
  2. A form element is defined with the @submit.prevent directive to handle form submission and prevent the default behavior (page reload).
  3. Two input fields for "Name" and "Email" are defined using <input> elements with respective id, v-model directives to bind data to the formData properties, and required attribute for mandatory input.

  4. Script Section:

  5. data() method initializes the formData object with empty name and email properties.
  6. The submitForm() method is defined to handle form submission. Currently, it logs the form data to the console.
  7. 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.