2017-08-03 8 views
0

私はVueJsを初めて使い、小さな栄養アプリを開発しています。現在、特定の栄養素に基づいて食品レシピを作りたいと考えています。

次のようにJSは次のとおりです。

 recommendFood: function() { 
 
      this.recs = {}; 
 
      var _this = this; 
 
      var getItem = function(ndbno,i,nid) { 
 
       _this.$http.get('http://127.0.0.1:3000/item?ndbno=' + ndbno).then(function(response) { 
 
         var someData = response.body; 
 
         var nutrients = someData.report.food.nutrients; 
 
         var item = someData.report.food; 
 

 
         item = this.addNutrientsToItem(item, nutrients); 
 
         this.recs[nid].push(item); 
 
       }); 
 
      }; 
 

 
      for (var i=0; i<this.low_nutrients.length; i++) { 
 
       this.low_nutrients[i].recs = []; 
 
       this.recs[this.low_nutrients[i].id] = []; 
 

 
       for (var k=0; k<this.low_nutrients[i].food_map.length; k++) { 
 
        var ndbno = this.low_nutrients[i].food_map[k]; 
 
        getItem(ndbno,i,this.low_nutrients[i].id); 
 
       } 
 
      } 
 
      console.log(this.recs) 
 
     }

私はthis.recsは栄養ID(私たちは保存すること)に相当している属性を持つオブジェクトになりたいです。各栄養素には、推奨される食品のIDを含むオブジェクトに添付されたfood_map配列があります。そのid(ndbno)をhttpリクエストに送信して、その食品推奨(item)のオブジェクトを受け取る必要があります。

this.recsオブジェクトは実際には(実際には自分のコードを書くための良い方法があるにもかかわらず)正確に設定されますが、ループを待っているので、オブジェクトが完成する前にhtmlがレンダリングされます。したがって、私のHTMLは空白です。約束の結果に更新されると、どのようにしてhtml上のrecを表示できますか?ここで

は私のHTMLです:

<div v-for="(nutrient, idx) in low_nutrients"> 
 
    <h2>{{nutrient.name}}</h2> 
 
    <div>Recommended Foods:</div> 
 
    <div> 
 
    <div>Recs:</div> 
 
    <div v-for="rec in recs[nutrient.id]">{{rec}}</div> 
 
    </div> 
 
</div>

目的のオブジェクトthis.recsは、次のようになります(それは、コンソールでこれを示してい):

this.recs = { 
 
    291: [{},{},{}], 
 
    316: [{},{},{}] 
 
}

答えて

0

問題はthis.recsが空になります。 Vue cannot detect property additionsなので、setを使用して新しいプロパティが追加されたことを伝える必要があります(これらのプロパティを無効にする)。

または、内容を変更するのではなく、新しいオブジェクトをthis.recsに再割り当てすることができます。

+0

OK、これは意味があると思います。this.recs [nid] .push(item)の代わりに、これを使用します:this。$ set(this.recs、nid、item)?これはまだ私に空のテンプレートを与えています。 Roy J – laura42

+0

私の解決策は、セットを使用することでした。私はこれを行いました.recsオブジェクト内に空白のオブジェクトを作成するには、recommendFood fnの最初のループで$ set(this.low_nutrients [i] .id]、{})をセットします。次に、getItemで、これを使用して、各栄養素オブジェクトにrecs w /を作成する$ set(this.recs [nid]、ndbno、item)を作成しました。 – laura42

関連する問題