【问题标题】:Is it possible to use v-bind:value or v-model for the object gotten from the network?是否可以对从网络获取的对象使用 v-bind:value 或 v-model ?
【发布时间】:2019-03-05 00:56:37
【问题描述】:

我想让VueApp 使用v-modelv-bind:value 作为从network api 获得的对象。
比如Vue appapi获取对象就这样

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

字段数量很大。
要使用 v-model='obj.field' ,我认为 Vue app 必须将数据定义如下。

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

我可以将v-model 用于从api 获得的对象,而没有定义vue app data 中的object 字段吗?
我需要这个的主要原因是字段数量很大,我不能确定所有字段都存在于obj 中。 (如以下示例中的field99
我认为在vue app data 中定义对象obj 的所有字段是不好的体验。

我想要的例子。

 //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' />

我怎样才能实现这个目标?

【问题讨论】:

    标签: vue.js vuejs2 v-model


    【解决方案1】:

    从远程api获取数据后设置数据,使用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' />
    

    【讨论】:

    • field99 不在obj 中时,上述方法有效吗?
    • 添加if条件判断属性是否在obj中
    猜你喜欢
    • 2020-06-26
    • 1970-01-01
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    • 2021-06-12
    相关资源
    最近更新 更多