jual ahmed
jual ahmed

Reputation: 448

Is it possible to use dynamic object key with v-model?

This is my data structure:

form: {
   email: '',
   password: ''
}

Now I want to use a loop and set the model dynamically with the form object.

<div class="my-1" v-for="(value,name, index) in form">
   <p class="capitalize"> {{ value }} </p>
   <!--<custom-input :value="value"></custom-input>-->
   <t-input v-model="dynamickmodel" class="w-full"/>
</div>

Upvotes: 1

Views: 395

Answers (1)

Dan
Dan

Reputation: 63059

Yes, by using a reference to the object and its key:

<t-input v-model="form[name]" class="w-full"/>

Changes to t-input should update the value for that key.

Demo:

new Vue({
  el: "#app",
  data() {
    return {
      form: {
        email: '',
        password: ''
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div class="my-1" v-for="(value, name, index) in form">
    <p class="capitalize"> {{ value }} </p>
    <input v-model="form[name]" class="w-full"/>
  </div>
</div>

Upvotes: 1

Related Questions