Vuetify: pass object attributes references to text fields in v-for

Viewed 530

I have the following object with data:

editedItem: {
  id: new Date().getTime(),
  dish_name: "",
  dish_type: "",
  ingredients: "",
  recipe: "",
}

I want to display it using for-loop.

Without for-loop I am displaying it as:

<v-card-text>
  <v-container>
    <v-row>
      <v-col cols="12" sm="6" md="4">
        <v-text-field
          v-model="editedItem.id"
          label="id"
        ></v-text-field>
        <v-text-field
          v-model="editedItem.dish_name"
          label="Dish name"
        ></v-text-field>
      </v-col>
      <v-col cols="12" sm="6" md="4">
        <v-text-field
          v-model="editedItem.dish_type"
          label="Dish type"
        ></v-text-field>
      </v-col>
      <v-col cols="12" sm="6" md="4">
        <v-text-field
          v-model="editedItem.ingredients"
          label="Ingredients"
        ></v-text-field>
      </v-col>
      <v-col cols="12" sm="6" md="4">
        <v-text-field
          v-model="editedItem.recipe"
          label="Recipe"
        ></v-text-field>
      </v-col>
    </v-row>
  </v-container>
</v-card-text>

I wanted to use for-loop:

<v-text-field
  v-for="(value, key, index) in editedItem"
  :key="index"
  v-model="value"
  :label="key"
>
</v-text-field>

but I am getting an error:

error  'v-model' directives cannot update the iteration variable 'value' itself 

What can I do to display it correctly?

1 Answers

You can use editedItem[key] in the v-model instead to refer to each attribute:

new Vue({
  el:"#app",
  vuetify: new Vuetify(),
  data() {
    return {
       editedItem: {
         id: new Date().getTime(),
         dish_name: "",
         dish_type: "",
         ingredients: "",
         recipe: "",
      },
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script><link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">

<v-app id="app">
  <div>
    <p>{{editedItem}}</p>
    <v-text-field
      v-for="(value, key, index) in editedItem"
      :key="index"
      v-model="editedItem[key]"
      :label="key"
    ></v-text-field>
  </div>
</v-app>

Related