vue中this失效问题

目录

1.示例代码

2.说明

3.解决方案


1.示例代码

    /** 删除按钮操作 */
    handleDelete(row) {
      debugger
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除国内低值货物入区主表编号为"' + ids + '"的数据项?').then(function () {
        debugger
        console.log(this);
        return delStorageInMaster(this.ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

2.说明

点击confirm的确认按钮之后,执行function方法中的内容,如果在方法内容要使用data中定义的一个变量,使用this.ids进行引用时,发现此时的this是undefined,无法直接进行引用,原因是因为

回调函数的内部的this并非指向当前的vue实例。

3.解决方案

(1)在方法执行之前存一下this,例

    /** 删除按钮操作 */
    handleDelete(row) {
      let _that = this;
      this.$modal.confirm('是否确认删除国内低值货物入区主表编号为"' + _that.ids + '"的数据项?').then(function () {
        return delStorageInMaster(_that.ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

(2)使用箭头函数,then后面不使用function,使用箭头函数

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除国内低值货物入区主表编号为"' + this.ids + '"的数据项?').then(() => {
        return delStorageInMaster(this.ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

(3)使用的变量存放在新的变量中,使用this.ids时,将其存放在ids变量中,后续处理不再使用this进行使用,而直接使用ids

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除国内低值货物入区主表编号为"' + ids + '"的数据项?').then(function () {
        return delStorageInMaster(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

4总结

箭头函数出现在es6,箭头函数里面没有this对象,此时的this对象指的是是外层的 this 对象,所以入如果在函数中要引用外面的this对象,推荐使用箭头函数。

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值