vue3.2版本需要子组件defineExpose暴露出方法,其他组件才可以使用
父组件app.vue
<template>
<button @click='childShow'>点击调用子组件方法</button>
<Comp ref='showComp'></Comp>
</template>
<script setup>
import { ref } from 'vue'
import Comp from './Comp.vue'
const showComp=ref(null)//这个时候获取了子组件Comp
const childShow=()=>{
showComp.value.show()//调用子组件的show方法
}
</script>
子组件Comp.vue
<template>
<div>我是子组件</div>
</template>
<script setup>
import { ref } from 'vue'
const show=()=>{
alert("我是子组件,我的show方法被调用了")
}
// 主动暴露childMethod方法
defineExpose({ show })
</script>