问题:下面的ajax请求会报错
$.ajax({
type: "POST",
dataType: "json",
url: "/list/add",
data: date,
success: function (res) {
if(200 === res.code) {
this.$message.success("保存成功");
}
},
error:function(){
this.$message.error("保存失败!");
}
});
$.ajax({
type: "POST",
dataType: "json",
url: "/list/add",
data: date,
success: function (res) {
if(200 === res.code) {
this.$message.success("保存成功");
}
}.bind(this),
error:function(){
this.$message.error("保存失败!");
}.bind(this)
});
问题原因是找不到this,再success的方法中,this的内容是发放中的内容
解决方式有两种
方式一:方法后面加 .bind(this) 将this指向vue的this
var that = this;
$.ajax({
type: "POST",
dataType: "json",
url: "/list/add",
data: date,
success: function (res) {
if(200 === res.code) {
that.$message.success("保存成功");
}
},
error:function(){
that.$message.error("保存失败!");
}
});
方式二:另一种方式就是再方法前定义一个that,使用that就好