繁体   English   中英

VueJS http获取请求

[英]VueJS http get request

尝试使用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);

我在我的机器上试了一个样品。你正在以错误的方式使用$ http。 引用docs.Since $ 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
    }


  })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM