2017-07-31 14 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'は文字列です。 'articles'メンバを含むオブジェクトとして' this.newsFeed'から始めましょう。 –

答えて

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); 
    }); 
} 

通話が終了した後filterAuthors方法が実行されるように次に、あなたのcreated関数を書く:

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

また、計算された変数でありますarticlesと名づけられており、したがって、でアクセスできますが、this.newsFeed.articlesではなくアクセスできます。

+0

答えがありがたいですが、 'this.articles'を試してもコンソールは' undefined'を返していますか? – sigil

+1

ただ答えを更新しました。つまり、 'filterAuthors'メソッドを実行する前にコール応答が来るのを待っているわけではありません。 – jeerbl

+0

それは動作します!どうもありがとうございます。私は何か愚かなことをしていることを知っていた。私はこれを受け入れられた答えとしてマークしました:) – sigil

関連する問題