V-model dynamic name in Vue 2 v-for loop

I am developing an application, and I use Vue 2javascript as a framework, inside the loop v-forI need the loop counter to be bound to the name of the v-modelelements, this is my code:

<div v-for="n in total" class="form-group">
    <input type="hidden" id="input_id" :name="'input_name_id['  + n  + ']'" v-model="form.parent_id_n" />
</div>  

I need to nbe a loop counter, for example, for the first element, it should be:

<div class="form-group">
    <input type="hidden" id="input_id" :name="'input_name_id[1]" v-model="form.parent_id_1" />
</div>

binding name attributeworks, but I have no idea how to make it work v-model?

+24
source share
4 answers

To use v-modelwith form.parent_id[n]:

  • form must be a data property.
  • form.parent_id must be an array.

Then you can do the following:

<div id="demo">
  <div v-for='n in 3'>
    <input v-model="form.parent_id[n]">
  </div>
  <div v-for='n in 3'>
    {{ form.parent_id[n] }}
  </div>
</div>

by setting up a vue instance, for example:

var demo = new Vue({
    el: '#demo',
    data: {
      form: {
        parent_id: []
      }
    }
})

fiddle .

+37

.

<div v-for="n in total" class="form-group">
   <input type="hidden" 
          id="input_id" 
          :name="'input_name_id['  + n  + ']'" 
          v-model="form['parent_id_' + n ]" />
</div> 
+7

Assuming what input_name_idis the string, you need to do:name="'input_name_id' + n"

Here is a working solution

0
source

Repeated text filed 10 times and separated by a v-model for each

<v-text-field
  v-for="(n,index) in 10"
  :key="index"
  v-model="pricing.name[n]"
  color="info"
  outline
  validate-on-blur
/>

data storage

data() {
    return {
     pricing:{
      name: [],
        }
      }
0
source

Source: https://habr.com/ru/post/1674637/


All Articles