2017-08-03 35 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(即我們存儲)屬性的對象。每個營養素都有一個food_map數組附加到包含id的食物的對象,這將是建議。我需要將這些ID(ndbno)發送到http請求以接收該食品推薦(項目)的對象。

this.recs對象實際上正確填充(儘管可能有更好的方法來編寫我的代碼),但是因爲它在循環中等待並承諾,所以html在對象完成之前呈現。因此,我的html是空白的。一旦更新了承諾結果,我如何在html上顯示recs?

這裏是我的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(項目),我會用:此$集(this.recs,NID項目)。?這仍然給我一個空白模板。 Roy J – laura42

+0

我的解決方案是使用該設置。我這樣做。$集(this.recs,[this.low_nutrients [I] .ID],{})重量/在recommendFood FN的第一環路來創建空白對象內的倫理委員會對象。然後,在getItem中,我使用了這個$ set(this.recs [nid],ndbno,item)來創建每個營養物體中的記錄。 – laura42