Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use v-bind:value or v-model for the object gotten from the network?

I want for VueApp to use v-model or v-bind:value for the object got from the network api.
For example, the Vue app gets the object from the api like this

 {
   field1:value1, field2:value2, ......... , field100:value100
 }

The number of fields are large.
To use v-model='obj.field' , I think that the Vue app has to define the data as following.

 new Vue({
   el:"#mainapp",
   data:{
    obj:{field:''}
   }
   ...
}

Could I use the v-model for the object gotten from the api without definition for the field of object in vue app data?
Main reason that I need this is that the number of fields are large and I couldn't be sure that all fields are existed in the obj. (like field99 in the below example)
I think to define all fields of the object, obj, in vue app data is bad experience.

Example I want.

 //script
  new Vue({
    el:"#mainapp",
    data:{
      obj:{}
    },
    created(){
       this.$http.get('urltoget_object')
      .then((res)=>{
         this.obj = res.body.data;  //this returns object by data field.
      }, (err)=>{}); 

    }
    ...
  }

<input type='text' v-model= 'obj.field100' />
<input type='text' v-model= 'obj.field99.netstedfield' />

How could I achieve this goal?

like image 224
Andrew Li Avatar asked Dec 27 '25 22:12

Andrew Li


1 Answers

set data after got data from remote api, make it responsive by using this.$set.

//script
new Vue({
  el:"#mainapp",
  data:{
    obj:{}
  },
  created(){
     this.$http.get('urltoget_object')
    .then((res)=>{
       this.obj = res.body.data;  //this returns object by data field.
       this.$set(this,'obj',res.body.data)
   }, (err)=>{}); 
  }
  ...
}

<input v-if="'field100' in obj" type='text' v-model= 'obj.field100' />
like image 88
Jean Ge Avatar answered Dec 30 '25 23:12

Jean Ge