错误如下:
NetData.vue?853e:26 Uncaught (in promise) TypeError: Cannot set property 'info' of undefined
at eval (NetData.vue?853e:26)
具体代码:
data () {
return {
info: null
}
},
methods: {
getData () {
// eslint-disable-next-line no-undef
console.log(this)
var self = this
this.axios.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(function (response) {
console.log(this)
self.info = response
console.log(response)
})
}
}
错误原因是:在then函数内部this为undefined,已经不是外面的vue实例,解决方法就是设置一个变量把this存起来
var self = this
后面的this.info变成self.info,之后就可以正常赋值了
另一种方式是使用箭头函数也可以实现上面的效果,就不需要另外定义一个变量了,更加简单