报错信息

代码如下:

created() {
	this.$axios
	.get("http://wthrcdn.etouch.cn/weather_mini?city=青岛")
	 .then(function(response){
	  this.city = response.data.data.city;
	  this.weather = response.data.data.forecast[0].type;
	  this.temperature = response.data.data.wendu + "℃"
	  })
	  .catch(function(error) {
	  	console.log(error);
	  });
}

原因:.then回调里的this指向的不是vue实例,所以报错。

解决:
1、修改this指向,原生js可以用.bind()方法
2、使用ES6 箭头函数

created() {
	this.$axios
	.get("http://wthrcdn.etouch.cn/weather_mini?city=青岛")
    .then(res => {
    this.city = res.data.data.city;
    this.weather = res.data.data.forecast[0].type;
    this.temperature = res.data.data.wendu + "℃"
    })
    .catch(err => {
    	console.log(err);
    });
 }
Logo

前往低代码交流专区

更多推荐