Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic V-model name in a v-for loop Vue 2

I am developing an application and I am using Vue 2 as the javascript framework, inside a v-for loop I need the counter of the loop to be bound to the v-model name of the elements, this 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 n to be the counter of the loop, 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>

the name attribute binding works but I have no idea how to get the v-model working as well?

like image 727
Siavosh Avatar asked Apr 12 '17 08:04

Siavosh


3 Answers

To use v-model with form.parent_id[n]:

  1. form should be a data property.
  2. form.parent_id should 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 having a vue instance setup like:

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

Check this fiddle for a working example.

like image 172
Amresh Venugopal Avatar answered Nov 14 '22 12:11

Amresh Venugopal


Another way achieve this is using bracket notation of accessing object property.

<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> 
like image 39
Mansur Anorboev Avatar answered Nov 14 '22 13:11

Mansur Anorboev


Repeated text filed 10 times and separated 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
/>

storing data

data() {
    return {
     pricing:{
      name: [],
        }
      }
like image 16
Atchutha rama reddy Karri Avatar answered Nov 14 '22 11:11

Atchutha rama reddy Karri