在做vue项目时用到了axios,但是发现axios请求之后的回调函数里this并不指向当前vue实例,从而导致浏览器报错。
出错代码及结果:
created : function(){
axios.get('static/data.json').then(function(res){
console.log(this) //undefined
this.user = res.data.user
})
}
(报错截图)
普通函数代码改版(正确):
created : function(){
var _this = this
axios.get('static/data.json').then(function(res){
console.log(this) //undefined
console.log(_this) //VueComponent {_uid: 1, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
_this.user = res.data.user
})
}
从以上结果来看,在created下的函数this指向的是当前创建的vue实例,而在这些函数内部使用例如axios与后台交互后回调函数的内部的this并非指向当前的vue实例;
若想拿到后台回传的数据更新data里的数据,不能在回调函数中直接使用this,而要用在外部函数定义的变量存储的this,也就是当前vue的实例。
箭头函数代码改版(正确):
created : function(){
axios.get('static/data.json').then((res) => {
console.log(this) //VueComponent {_uid: 1, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
this.user = res.data.user
})
}
箭头函数相当于匿名函数,并且简化了函数定义。看上去是匿名函数的一种简写,但实际上,箭头函数和匿名函数有个明显的区别:箭头函数内部的this是词法作用域,由上下文确定。此时this在箭头函数中已经按照词法作用域绑定了。很明显,使用箭头函数之后,箭头函数指向的函数内部的this已经绑定了外部的vue实例了.