问题描述:
我在使用axios发送异步GET请求后,对响应数据进行处理时遇到了一个问题,
该部分源码如下:
.then(function(result){
console.log(result);
this.textOutput = result.data.trans_result[0].dst;
console.log(this.textOutput);
if(result.data.status === 504){
alert('Fail to translate with baidu API!');
}
})
我想将result.data里面的字符串字段内容赋值给Vue实例中的textOutput属性,此时报错:
当时并没有想到是因为网络请求中this的作用域问题,后来在csdn上找到答案,
csdn上的解决办法
主要原因是:this在网络请求的异步代码块中的this与当前数据所在类的this不是一个作用域,所以会导致undefined。 推荐使用箭头函数,或者在后方加bind(this),
我选择了箭头函数,下面代码是我经过修改过后的样子:
then((result) =>{
console.log(result);
this.textOutput = result.data.trans_result[0].dst;
console.log(this.textOutput);
if(result.data.status === 504){
alert('Fail to translate with baidu API!');
}
})
Vue中的箭头函数与function()有什么区别呢?
我参考了这篇文章
1、this指向问题:
(1)funtion普通函数中this指向window: 所以如果需要在function函数中使用this对象,需要事先把this对象赋值给其他变量,如:
let self = this;
this.getReportId().then(function(result) {
self.id = result;
alert(self.id);
});
(2)箭头函数中this指向vue实例: 箭头函数相当于匿名函数,并且简化了函数定义。看上去是匿名函数的一种简写,但实际上,箭头函数和匿名函数有个明显的区别:箭头函数内部的this是词法作用域,由上下文确定。 此时this在箭头函数中已经按照词法作用域绑定了。很明显,使用箭头函数之后,箭头函数指向的函数内部的this已经绑定了外部的vue实例了。如:
this.getReportId().then(result => {
this.id = result;
alert( this.id);
});
2、写法转换:以下两种写法效果是一样的:
formatter: function(params) {
return params.name + ' 已接入: ' + params.data.num[2];
}
formatter: params => {
return params.name + ' 已接入: ' + params.data.num[2];
}