2017-07-31 30 views
1

我想遍歷包含對象的數組,並從這些對象中獲取作者姓名列表。Vue 2 - 如何訪問在方法內計算

要做到這一點,我想寫一個方法,我會forEach()通過。但我似乎無法訪問我的包含數組的計算屬性,當我console.log(articles)console.log(this.newsFeed)它返回undefined或只是空白。

顯然,我做錯了什麼,但我不明白是什麼...

這裏是我的代碼:

new Vue({ 
    el: '#feed', 
    data: { 
     newsFeed: "", 
}, 
created: function() { 
    console.log('running'); 
    this.getData(); 
    this.filterAuthors(); 
}, 
computed: 
{ 
    articles: function() { 
     var articles = this.newsFeed.articles; 
     return articles; 
    }, 
}, 
methods: 
{ 
    getData: function() { 
     var newsFeed = this.$http.get('https://newsapi.org/v1/articles?source=the-next-web&sortby=latest&apikey='+ apikey).then(response => { 
      this.newsFeed = response.body; 
     }, response => { 
      console.error(error); 
     }); 
    }, 
    filterAuthors: function() { 

     var articles = this.newsFeed.articles; 
     var authorsArray = []; 

     console.log(articles); 

     // commented out while troubleshooting above 
     // articles.forEach(function(article) { 
     // // var authors = article.author; 
     // // authorsArray.push(authors); 
     // console.log(authors); 
     // }); 

     // return authorsArray; 
    } 
} 
}); 
+3

它不是'this.newsfeed.articles',它只是'this.articles'。 –

+0

謝謝 - 但我試過改用'this.articles'並且控制檯返回'undefined'? – sigil

+0

這是因爲你的計算結果也指'this.newsFeed.articles',但'this.newsFeed'是一個字符串。以'this.newsFeed'作爲包含'articles'成員的對象開始。 –

回答

1

HTTP調用你使使用this.$http是異步的。由於它是異步的,你需要告訴你的代碼等待直到調用完成。

getData功能,你可以寫:

getData: function() { 
    return this.$http.get('https://newsapi.org/v1/articles?source=the-next-web&sortby=latest&apikey='+ apikey) 
    .then(response => { 
     this.newsFeed = response.body; 
    }, err => { 
     console.error(err); 
    }); 
} 

然後再編寫created功能,以便filterAuthors方法執行通話結束後:

created: function() { 
    console.log('running'); 
    this.getData() 
    .then(() => { 
     this.filterAuthors(); 
    }); 
} 

而且,計算變量名稱爲articles,因此可以通過this.articles訪問,而不是this.newsFeed.articles

+0

感謝您的答案,但是當我嘗試'this.articles'時,控制檯正在返回'undefined'? – sigil

+1

剛剛更新了答案。事情是,在執行'filterAuthors'方法之前,你並沒有等待調用響應。 – jeerbl

+0

它的工作原理!非常感謝。我知道我在做一些愚蠢的事情。我已將此標記爲接受的答案:) – sigil