vue3 父组件直接调用子组件的方法
时间: 2025-02-07 09:10:03 浏览: 22
Vue3 父组件调用子组件方法
在 Vue 3 的组合式 API 中,实现父组件调用子组件的方法主要分为三个部分:
子组件定义方法并暴露给外部使用
子组件需要先定义好要被外界访问的方法,并通过 defineExpose
显式声明哪些属性或方法对外可见[^1]。
<!-- ChildComponent.vue -->
<script setup>
import { defineExpose } from 'vue'
function childMethod() {
console.log('Child method called')
}
// 将特定的方法暴露出去供父级调用
defineExpose({
childMethod
})
</script>
<template>
<div>这是一个子组件</div>
</template>
父组件创建引用并与子组件关联
父组件利用 <template ref>
属性来获取对子组件实例的引用,从而能够在其作用域内操作该子组件实例上的公开接口。
<!-- ParentComponent.vue -->
<script setup>
import { ref, onMounted } from 'vue'
import ChildComponent from './ChildComponent.vue'
const childRef = ref(null)
onMounted(() => {
if (childRef.value && typeof childRef.value.childMethod === 'function') {
childRef.value.childMethod()
}
})
</script>
<template>
<div>
<!-- 使用ref绑定到子组件上 -->
<ChildComponent ref="childRef"></ChildComponent>
</div>
</template>
上述代码展示了完整的父子组件间通信模式,在此过程中确保了良好的封装性和模块化设计原则。当页面加载完成后,父组件会尝试调用子组件中的 childMethod()
函数。
相关推荐














