【问题标题】:VueJS http get requestVueJS http 获取请求
【发布时间】:2018-05-04 16:15:27
【问题描述】:

尝试使用 Vue js 发送 http get 请求。看不出逻辑有任何问题,虽然使用 vuejs 没有太多经验。

不断收到这两个错误:

[Vue 警告]:挂载钩子错误:“TypeError:无法读取属性 'get' of undefined"

和

TypeError: 无法读取未定义的属性“get”。

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资源更新了代码,错误消失了,但控制台不会记录任何数据,可能是什么问题?

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

【问题讨论】:

标签: javascript http vue.js


【解决方案1】:

我在我的机器上尝试了一个示例。您以错误的方式使用 $http。参考文档。由于 $http 解决了一个承诺,它的回调可以在 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
    }


  })

【讨论】:

  • 仍然没有得到任何数据
  • 你能成功请求吗??或者您在发送请求时是否遇到任何错误?你能在调试工具中发送来自网络面板的响应截图吗?
  • 请求没有错误,但也没有返回数据
  • 运行你的代码,仍然没有返回任何数据。这段代码虽然对我有用 this.$http.get('api.openweathermap.org/data/2.5/find?q=' + this.userInput + this.apiKey).then((data) => {},但不熟悉 .then 函数的作用。
猜你喜欢
  • 2019-02-08
  • 1970-01-01
  • 1970-01-01
  • 2020-10-23
  • 2012-03-09
  • 2015-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多