jdost_26
jdost_26

Reputation: 415

How to handle v-model in dynamic input fields

I have a form where the user has the option to click an "Add" button and input content into new fields. I've currently dynamically generated the v-model for the fields, but I realized I need to register/return each of them in the setup function to use them.

How do I generate and register/return v-models for the different input fields if I don't know how many fields the user will decide to add?

<div
    v-for="(content, i) in contentFields"
    :key="i"
>
  <div>Content {{ i }}</div>
        <q-input
          :v-model="`contentName_` + i"
          outlined
          type="text"
          dense
        />
 </div></div>


  

Upvotes: 0

Views: 905

Answers (1)

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23480

Take a look at following snippet with simple dynamic v-models pls:

new Vue({
  el: "#demo",
  data() {
    return {
      contentFields: [{name: '', desc: ''}]
    }
  },
  methods: {
    addInput() {
      let newI = this.contentFields.length
      this.contentFields.push({name: '', desc: ''})
    },
    setD() {
      console.log(this.contentFields)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <button @click="addInput">add</button>
  <div v-for="(content, i) in contentFields" :key="i">
    <div>Content {{ i }}</div>
      <input
        v-model="content.name"
        outlined
        type="text"
        dense
        @change="setD"
      />
      <input
        v-model="content.desc"
        outlined
        type="text"
        dense
        @change="setD"
      />
  </div>
</div>

Upvotes: 1

Related Questions