报错:Uncaught (in promise) TypeError: Cannot read property 'alert' of undefined
检查代码十几遍,发现没有问题,但是运行又报错,这是为什么?--------->这就是javascript中this的指向问题
代码如下:
console.log(this) //这里指向的vue
this.$axios.post('http://127.0.0.1:8000/my/register/',{"username":this.username,"password":this.password1,"email":this.email}).then(
function (res) {
if(res.data === "Register OK"){
this.$mui.alert('注册成功', '信息','确定');
}else{
this.$mui.alert('该用户名已存在', '警告','确定');
}
}
).catch(function (res) {
console.log(this) //这里指向的window
this.$mui.alert('注册失败', '警告','确定')
})
报错在这一行,提示alert有问题,this.$mui.alert('注册失败', '警告','确定')
然而代码确实没有问题,这时候就要想到是this的问题,使用控制台输出发现两个this指向不同
解决办法:
方法一:在最外层加上如下代码,将this赋值给另一个变量
这种方法有点low
var _this= this; //在最外层这里加上这行代码
this.$axios.post('http://127.0.0.1:8000/my/register/',{"username":this.username,"password":this.password1,"email":this.email}).then(
function (res) {
if(res.data === "Register OK"){
_this.$mui.alert('注册成功', '信息','确定');
}else{
_this.$mui.alert('该用户名已存在', '警告','确定');
}
}
).catch(function (res) {
_this.$mui.alert('注册失败', '警告','确定')
})
方法二:使用箭头函数
此时两个this都指向VueComponent,且程序正常运行。高级做法0.0
this.$axios.post('http://127.0.0.1:8000/my/register/',{"username":this.username,"password":this.password1,"email":this.email}).then(
(res)=> {
console.log(this);
if(res.data === "Register OK"){
console.log(res);
this.$mui.toast('注册成功', '信息','确定');
}else{
this.$mui.alert(res.data, '警告','确定');
}
}
).catch(
(res)=> {
console.log(this);
this.$mui.alert('注册失败', '警告','确定')
}
)
}
最后解决图: