[Vuejs]-VueJS Dynamic v-model target

0πŸ‘

βœ…

Vue is still Javascript – you can access properties with strings

let v = new Vue({
  el:'#someEl',
  data(){
    const self = this
    return {
    parentval1:'foo',
    parentVal2:'bar',
    children:[
      {childVal1:'bax', modelAttr:'parentVal1'},
      {childVal2:'bix', modelAttr:'childVal1'},
      {childVal3:'boom', modelAttr:'childVal2'}
    ],
    whichModelField: {
      get parentVal1(){
           return self.parentval1
      },
      set parentVal1(val){
           self.parentval1 = val
      },
      get childVal1(){
        return self.children[0]['childVal1']
      },
      set childVal1(val){
        self.children[0]['childVal1'] = val
      },
      get childVal2(){
        return self.children[1]['childVal2']
      },
      set childVal2(val){
        self.children[1]['childVal2'] = val
      }
      
    }}
  }
})
.as-console-wrapper {
  height: 0px !important
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="someEl">
  <p id='parent'>
    <input id="1" placeholder="test" v-model="whichModelField['parentVal1']"/>
  </p>
  <p id='child1' v-for="child in children">
    <input  :placeholder="child.modelAttr" v-model="whichModelField[child.modelAttr]"/>
    
  </p>
</div>

0πŸ‘

Is this is what you are looking for:

new Vue({
    el:'#app',
    data:{
        parent:'',
        child:''
    },
    watch:{
        parent: function(value){this.child = value}
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <p id='parent'>
    <input id="1" placeholder="test" v-model='parent'/>
  </p>
  <p id='child1'>
    <input id="1" placeholder="test"  v-model='child' :value='parent'/>
    <!-- 1 and parent>input#1 should be bound to same value -->
    <input id="2" placeholder="more test" :value='child'/>
    <!-- 2 and 3 should be bound to same value -->
    <input id="3" placeholder="more test" :value='child'/>
  </p>
</div>

0πŸ‘

I separated between the first child and the others because you want to do 2-way binding only in the parent ant the first child, you don’t want that the children will update the parent:

new Vue({
  el:'#app',
  data:{
    parent:'foo',
    child:'bar',
    children:[
      {placeHolder:'bax'},
      {placeHolder:'bix'},
      {placeHolder:'boom'}
    ]
  },
  watch:{
      parent: function(value){debugger; this.child = value}
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input id="1" v-model="parent" placeholder="test"/>
  <input v-model="child"
         :id="0"
         :placeholder="children[0].placeHolder" />

  <input  v-for="i in children.length - 1"
         :value="child"
         :id="i + 1"
         :placeholder="children[i].placeHolder" />
</div>

Leave a comment