我希望在点击事件触发时,通过$refs调用某个组件的方法,并执行全局vue实例上$message方法
// 父组件
import AddRole from './AddRole';
export default defineComponent({
setup() {
const addRoleRef = ref<InstanceType<typeof AddRole>>();
const handleAddClick = function () {
console.log(addRoleRef); // 打印出来addRoleRef.value是null
addRoleRef.value?.show('add');
// $message是挂在app.config.globalProperties的全局变量
this.$message.success('删除成功');
};
},
render(){
return (
<div>
<AddRole ref="addRoleRef" />
</div>
)
}
})
// 子组件 AddRole.tsx
export default defineComponent({
setup(_props: Common.Params, { expose }) {
const visible = ref<boolean>(false);
const show = function () {
visible.value = true;
};
expose({show});
return {
show,
};
},
render() {
return (
<a-modal
title="弹框"
visible={visible}
width="420px"
cancelText="取消"
okText="确定"
>
</a-modal>
);
},
});
但是在setup中我拿不到this和子组件实例
找到问题了,ref绑定的子组件实例和getCurrentInstance获取的上下文即当前组件实例,都需要在setup里导出
值得注意的是,getCurrentInstance()得到的上下文对象包含ctx、proxy等多个属性, ctx和proxy相当于Vue2的this,但是ctx只能在开发环境使用,打包后就会失效