我想遍歷包含對象的數組,並從這些對象中獲取作者姓名列表。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;
}
}
});
它不是'this.newsfeed.articles',它只是'this.articles'。 –
謝謝 - 但我試過改用'this.articles'並且控制檯返回'undefined'? – sigil
這是因爲你的計算結果也指'this.newsFeed.articles',但'this.newsFeed'是一個字符串。以'this.newsFeed'作爲包含'articles'成員的對象開始。 –