Skip to content

How to Create Multiple Forms Through Loops?

This guide demonstrates how to use form-create to create multiple forms in loops and implement dynamic form addition, reset, and submission. We'll use mock data to simulate form data from APIs and provide detailed code examples and explanations.

Code Explanation

  • Button Area: Contains three buttons for fetching form data, adding new forms, and resetting forms. Button @click events are bound to corresponding methods.

  • Loop Rendering Forms: Use the v-for directive to iterate through the forms array and render each form. Each form is generated using the form-create component, with the key set to the unique form.id.

  • Form Creation: The createForm function generates form configurations with default data. idCounter is used to ensure each form has a unique id.

  • Fetch Form Data: The fetchFormData method uses mockData to simulate fetching data from an API and initializes the forms list.

  • Add Form: The addForm method adds a new empty form to the form list.

  • Reset Forms: The resetForms method re-fetches data from mock data and resets the forms list.

  • Submit Forms: The handleSubmit method validates all form data and outputs the data after successful validation.

Notes

  • Mock Data: In production, replace mockData with real API requests.
  • Unique Identifier: Use idCounter to ensure each form has a unique id; avoid using the index as the key.
  • Form Validation: In the handleSubmit method, use Promise.all to ensure all forms pass validation.

FormCreate is an open-source project released under the MIT License. Free for personal and commercial use.