因this的指向问题而报错分析及解决办法

报错: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('注册失败', '警告','确定')
    }
)
}

最后解决图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值