[Vuejs]-Vue dynamic form elements in for loop

0👍

Simply define an empty array for the form fields, e.g. return { formFields: [] }. Then add as many values in this array as input fields you want to render on the screen:

<template>
  <form>
    <input v-for="(field,index) in formFields" :key="index" v-model="fields[index]" type="text">
  </form>
</template>

<script>
export default
{
  data()
  {
    return {
      formFields: []
    };
  },
  mounted()
  {
    for (let i = 1; i <= 10; i++) this.formFields.push('');
  }
}
</script>

If you need different types of input fields – you will need to use array of objests instead of strings, and encode the field type as a property inside each of these objects.

Leave a comment