VueJS 的 HTTP GET 请求

7
尝试使用Vue js发送http get请求。逻辑上没有发现任何问题,但我对vuejs的使用经验不是很丰富。
一直遇到这两个错误:
[Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'get' of undefined"

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 resource更新了代码,错误已经消除,但是无法记录任何数据,可能出了什么问题?

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

编辑: 这段代码可用,虽然不太理解 .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 - Casper
但是不要使用vue-resorce包。它现在已经被弃用了。阅读有关替代方案的内容:https://medium.com/the-vue-point/retiring-vue-resource-871a82880af4 - user6748331
已安装vue-resource并运行:var Vue = require('vue');在代码中使用Vue.use(require('vue-resource'));,现在我收到了“require未定义”的错误提示。 - Znowman
1个回答

8

我在我的机器上尝试了一个例子。你使用了错误的方式来使用 $http,请参考文档。因为 $http 返回一个 promise,所以它的回调函数应该在 then 函数中处理。下面这个方式对我有效:

 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
    }


  })

仍未获取到任何数据。 - Znowman
你能成功发送请求吗?还是在发送请求时遇到了错误?你能否在调试工具的网络面板中发送响应的截图。 - Manav Mandal
请求没有出现错误,但是也没有返回任何数据。 - Znowman
运行了你的代码,但仍未返回任何数据。不过这段代码在我的电脑上是可以工作的。使用了 this.$http.get('http://api.openweathermap.org/data/2.5/find?q=' + this.userInput + this.apiKey).then((data) => {},但我不太熟悉 .then 函数的作用。 - Znowman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接