我们使用ajax的时候,会发现在ajax,success和error方法里面使用this有问题,这是因为ajax里使用的this是指的ajax本身这个对象了,并不是ajax外面的对象。解决方法有2种,如果项目不考虑浏览器兼容的话,推荐是同es6箭头函数,方便很多,注意ide的js版本设置
(1)定义新的变量保存外边的this,
var _this = this;
$.ajax({
url: '/demo/user/login',
type: 'post',
data: {'username':this.username,'password':this.password},
dataType: 'json',
success: function (res) {
if (res.code == 0) {
location.href = './index.html';
} else {
_this.$message({
message: res.msg,
type: 'warning'
});
}
},
error: function (res) {
_this.$message.error('操作失败');
}
});
(2)使用es6箭头函数
$.ajax({
url: '/demo/user/login',
type: 'post',
data: {'username':this.username,'password':this.password},
dataType: 'json',
success: (res) => {
if (res.code == 0) {
location.href = './index.html';
} else {
this.$message({
message: res.msg,
type: 'warning'
});
}
},
error: (res) => {
this.$message.error('操作失败');
}
});
至于为什么箭头函数能解决这个问题,以下这段话网上找的,并非原创
1. 在箭头函数出现之前,每个新定义的函数都有其自己的this值(例如,构造函数的 this 指向了一个新的对象;严格模式下的函数的 this 值为 undefined;如果函数是作为对象的方法被调用的,则其 this 指向了那个调用它的对象)。
2. 箭头函数没有自己的this,不会新产生自己作用域下的this,箭头函数里面的this指向它外层的环境里的this,它没有自己的this。arguments,super和new.target等对象。此外,箭头函数总是匿名的。