Use v-model in a v-for loop

126 Views Asked by At

I have a component with the following data -

data() {
    return {
        name: '',
        age: '',
    }
}

I then define a method like the following -

formData() {
   const data = [
      {label: 'Name', model: this.name},
      {label: 'Age', model: this.age},
   ]
   return data
}

In my template, I am writing a v-for loop accessing the formData() to render the HTML. (I'm doing it this way because there will be ~50 form fields like name and age and the HTML is the same for every form field).

<md-table>
    <md-table-row v-for="d in formData()" :key="d.label">
        <md-table-cell>{{d.label}}</md-table-cell>
        <md-table-cell>
            <md-field>
                 <md-input v-model="d.model"></md-input>
            </md-field>
        </md-table-cell>
    </md-table-row>
</md-table>

This template renders fine. However, the models are not bound, because the values of name and age does not change in the data if the user enters in the input fields.

I am pretty sure this is because when declaring formData(), I am actually passing the values of the data in the model. Is there a way I can actually pass the model, so that the template v-models bind?

1

There are 1 best solutions below

0
Tordek On

Use props:

In the child component define:

props: ['name', 'age']

and remove the data element.