在vue的created钩子中使用请求到的数据给data里的变量赋值,报错‘undefined’
代码如下:created() {this.$axios.get(“http://wthrcdn.etouch.cn/weather_mini?city=青岛”).then(function(response){this.city = res.data.data.city;this.weather = res.data.data.forecast[0].type;this.temperature =
·
代码如下:
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);
});
}
更多推荐
已为社区贡献1条内容
所有评论(0)