简体   繁体   English

VueJS http获取请求

[英]VueJS http get request

Trying to send an http get request using Vue js. 尝试使用Vue js发送http get请求。 Can't see any problems with the logic, not too experienced using vuejs though. 看不出逻辑上的任何问题,虽然使用vuejs也没有太多经验。

Keep getting these two errors: 继续得到这两个错误:

[Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'get' of undefined" [Vue警告]:挂钩错误:“TypeError:无法读取属性'get'of undefined”

and

TypeError: Cannot read property '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();
  }
});

Updated the code using vue resource, the errors are gone but it won't console log any data, what could be wrong? 使用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();
  }
});

EDIT: This code works, don't really understand the .then function though and why the request won't work with the callback function but the .then function does. 编辑:这段代码有效,但是并不真正理解.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);

I tried a sample on my machine .you are using $http in wrong way. 我在我的机器上试了一个样品。你正在以错误的方式使用$ http。 refer the docs.Since $http resolves a promise its callback can be handled inside a then function. 引用docs.Since $ http解析一个promise,它的回调可以在then函数内处理。 This worked for me: 这对我有用:

 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