vue3 组合式父组件调用子组件方法
时间: 2023-11-25 17:04:46 浏览: 104
在Vue3中,父组件可以通过组合式API中的expose
和ref
来调用子组件的方法。具体步骤如下:
- 在子组件中,使用
ref
来创建一个子组件实例的引用,并在expose
中暴露需要被父组件调用的方法。
<template>
<div>子组件</div>
</template>
<script>
import { ref, defineComponent } from 'vue'
export default defineComponent({
setup() {
const childRef = ref(null)
const childMethod = () => {
console.log('子组件方法被调用')
}
// 暴露需要被父组件调用的方法
expose({
childMethod,
})
return {
childRef,
}
},
})
</script>
- 在父组件中,使用
ref
来创建一个子组件实例的引用,并使用onMounted
钩子函数来获取子组件实例,并调用子组件的方法。
<template>
<div>
<ChildComponent ref="childRef" />
<button @click="callChildMethod">调用子组件方法</button>
</div>
</template>
<script>
import { ref, onMounted } from 'vue'
import ChildComponent from './ChildComponent.vue'
export default {
components: {
ChildComponent,
},
setup() {
const childRef = ref(null)
// 获取子组件实例
onMounted(() => {
childRef.value = childRef.value || {}
childRef.value = childRef.value.$refs.childRef
})
// 调用子组件方法
const callChildMethod = () => {
childRef.value.childMethod()
}
return {
childRef,
callChildMethod,
}
},
}
</script>
在父组件中,我们使用ref
来创建一个子组件实例的引用,并在onMounted
钩子函数中获取子组件实例。然后,我们可以通过childRef.value.childMethod()
来调用子组件的方法。
相关推荐


















