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>

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.

2 answers

  • answered 2021-05-03 17:58 duckbrain

    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>

  • answered 2021-05-03 18:03 Naren

    item is value of your editedItem.keys(days,...), for objects iteration (v-for), second param is the actual key.

    v-for="(value, key) in object".

    So, change your code like this, it will work

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