Skip to content
Advertisement

Trying to add v-model textboxes in a v-for loop of an Object

I have a bit of a problem. I am trying to loop through an object in order to create textboxes dynamically, rather than manually writing out the fields.

editedItem: {
        day: "",
        "9.00 - 10.00": "",
        "10.00 - 11.00": "",
        "11.00 - 12.00": "",
        "12.00 - 13.00": "",
        "13.00 - 14.00": "",
        "14.00 - 15.00": "",
    },

Then in the template.

<v-col cols="12" sm="6" md="4" v-for="item in editedItem" :key="item">
     <v-text-field v-model="item"></v-text-field>
</v-col>

That’s not working. I have also tried to loop through the keys (editedItem.keys), but I can’t seem to assign just “item” to the v-model.

Advertisement

Answer

You can think of the template behaving like this:

for (let i in editedItem) {
  let item = editedItem[i];
  // On @input
  item = $event;
}

It’s editing a copy. You can resolve the issue by referencing the v-model by index.

<v-col cols="12" sm="6" md="4" v-for="(item, index) in editedItem" :key="item">
     <v-text-field v-model="editedItem[index]"></v-text-field>
</v-col>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement