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 指向当前的组件实例。所以,handleClose 的 this 从一开始就被 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');
}
}
}
1564

被折叠的 条评论
为什么被折叠?



