2017-11-21 17 views
1

Vue jsを使用してhttp取得要求を送信しようとしています。しかし、vuejsを使用しても経験がない、ロジックに問題は見られません。VueJS http get request

これら2つのエラーになってください:

[Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'get' of undefined"

VUEのリソースを使用してコードを更新しました

TypeError: Cannot read property 'get' of undefined.

var owm = new Vue({ 
    el: '#owm', 
    data: { 
    debug: true, 
    weather: [] 
    }, 
    methods: { 
    loadWeather: function() { 
     this.$http.get('http://api.openweathermap.org/data/2.5/find?q=stockholm&type=like&appid=766b78c39446a8fa6313c3b7b2063ade', function(data, status, request){ 
     if(status == 200) 
     { 
      this.weather = data; 
      console.log(this.weather); 
     } 
     }); 
    } 
    }, 
    mounted: function() { 
    this.loadWeather(); 
    } 
}); 

を、エラーがなくなっているが、それはすべてのデータを記録し、コンソールはありません、どのような間違っていますか?

Vue.use(VueResource); 
var owm = new Vue({ 
    el: '#owm', 
    data: { 
    weather: [] 
    }, 
    methods: { 
    loadWeather: function() { 
     this.$http.get('http://api.openweathermap.org/data/2.5/find?q=stockholm&type=like&appid=[API KEY]', function(data, status, request){ 
     if(status == 200) 
     { 
      this.weather = data; 
      console.log(this.weather); 
     } 
     }); 
    } 
    }, 
    mounted: function() { 
    this.loadWeather(); 
    } 
}); 

EDIT: このコードは動作しますが、実際にも.then機能を理解していないと、なぜ要求がコールバック関数では動作しませんが、.then機能はありません。

this.$http.get('http://api.openweathermap.org/data/2.5/find?q=stockholm&type=like&appid=[API KEY]').then((data) => { 
    this.weather = data; 
    console.log(this.weather); 
+1

、これを確認https://stackoverflow.com/questions/42387414/uncaught-typeerror-cannot-read-property-get-of-undefined-in-vuejs – CasperSL

+0

しかし、使用しないでください'vue-resorce'パッケージです。今は廃止されました。代替案についてはこちらを参照してください。https://medium.com/the-vue-point/retiring-vue-resource-871a82880af4 – WaldemarIce

+0

vueリソースがインストールされ、実行されています。var Vue = require( 'vue'); Vue.use(require( 'vue-resource'));コードでは、今、私は "必要が定義されていません"というエラーが表示されます – Znowman

答えて

1

私のマシンでサンプルを試しましたが、間違った方法で$ httpを使用しています。 docs.Since $ httpが約束を解決するので、その関数内でそのコールバックを処理することができます。これが私の仕事:

loadWeather: function() { 
    var self=this; 
    this.$http.get('http://api.openweathermap.org/data/2.5/find?q=stockholm&type=like&appid=766b78c39446a8fa6313c3b7b2063ade').then(function(response){ 
    if(response.status == "200"){ 
     console.log(response); 
    self.weather = response.data.list[0].weather // use self instead of this 
    } 


    }) 
+0

まだすべてのデータを取得していません – Znowman

+0

リクエストを正常に行うことができますか?またはリクエストを送信中にエラーが発生しますか?あなたはデバッグツールのネットワークパネルからの応答のスクリーンショットを送ることができます。 –

+0

リクエストでエラーは発生しませんが、データは返されません – Znowman