vue prop传递函数 this指向

element Dialog组件

<el-dialog
  title="提示"
  :visible.sync="dialogVisible"
  width="30%"
  :before-close="handleClose">
  <span>这是一段信息</span>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
  </span>
</el-dialog>
handleClose(done) {
        this.$confirm('确认关闭?')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      }

子组件中调用handleClose,this的指向指哪,在vue中,this的指向指向父组件
在js中,我们把一个函数的引用传递,在调用这个函数时,会根据上下文环境在确定当前的this指向,上面的案例中,this的指向应该指向子组件
出现这种情况的原因是 vue在初始化时,methods 对象里的所有函数都会被 Vue 自动绑定,使其 this 指向当前的组件实例。所以,handleClosethis 从一开始就被 Vue 锁定为了父组件实例。
而element源码中也没有对this进行更改,因此this的指向为父组件

handleClose() {
      if (typeof this.beforeClose === 'function') {
        // 直接调用了 props 传进来的函数
        // 并没有使用 .call(someOtherThis) 或 .apply(someOtherThis)
        this.beforeClose(this.hide); // 传入了一个 done 函数
      } else {
        this.hide();
      }
    },
    hide(cancel) {
      if (cancel !== false) {
        this.$emit('update:visible', false);
        this.$emit('close');
      }
    }
  }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

紫霞仙子我爱你

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值