子组件
component-a
component-a 暴漏方法,供外部调用
<template>
<div class="com-a" @click="onClose"></div>
</template>
<script setup>
const emits = defineEmits([
'close'
])
function notify() {
console.log('click')
}
function onClose() {
emits('close')
}
defineExpose({
notify // 暴漏的方法
})
</script>
- 子组件对外暴露了
notify
事件,供父组件调用 - 子组件触发了
close
事件,供父组件接收
父组件
component-b
调用 component-a 组件中的方法
<template>
<component-a ref="comRef" @close="onClose"></component-a>
</template>
<script setup>
const comRef = ref();
onMounted(() => {
const instance = comRef.value;
if(typeof instance?.notify === 'function') {
instance.notify()
}
})
function onClose() {
console.log('父组件方法被调用')
}
</script>
- 父组件主动调用
notify
方法 - 父组件接收
close
回调方法