Home > Net >  Vue dynamic form elements in for loop
Vue dynamic form elements in for loop

Time:02-18

In a vue component I want to generate dynamic input elements in a for loop and bind them to the data.form element.

data() {
    return {
        form: {}
    }
}

<b-form-checkbox v-model="form[key]['amount']" type="checkbox" :value="key"></b-form-checkbox>

How can I deal with this, what I tried:

form.amount[key] // is working, but not really the best data structure, and the array is populated with null values for each for loop entry on init ...
form[key]['amount'] // not working

// the working example I mentioned is structured this way
form: {
  amount: [],
}

Maybe someone can help me with this ...

CodePudding user response:

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.

  • Related