我想遍历包含对象的数组,并从这些对象中获取作者姓名列表。
为此,我想编写一个我将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;
}
}
});
Run Code Online (Sandbox Code Playgroud)
您使用的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);
});
}
Run Code Online (Sandbox Code Playgroud)
然后编写created函数,以便filterAuthors在调用完成后执行该方法:
created: function() {
console.log('running');
this.getData()
.then(() => {
this.filterAuthors();
});
}
Run Code Online (Sandbox Code Playgroud)
另外,计算变量已命名articles,因此可以通过this.articles而不是进行访问this.newsFeed.articles。
| 归档时间: |
|
| 查看次数: |
5730 次 |
| 最近记录: |