vue中父组件调用子主键的方法
时间: 2024-12-26 12:19:40 浏览: 28
实现父组件调用子组件方法的方式
在 Vue 3 组合式 API 中,实现父组件调用子组件的方法涉及几个关键步骤。这些步骤确保了父子组件之间的交互既安全又高效。
子组件定义并暴露方法
子组件需先定义所需执行的方法,并通过 defineExpose
显式声明哪些属性或方法对外可见[^1]:
<script setup>
import { defineExpose } from 'vue'
function childMethod() {
console.log('Child method called')
}
defineExpose({
childMethod
})
</script>
<template>
<!-- 子组件模板 -->
</template>
父组件创建引用并与子组件关联
父组件应利用 <script setup>
和 ref
来获取对子组件实例的访问权限。这允许父组件持有指向特定子组件实例的引用对象:
<template>
<div>
<!-- 使用 ref 属性绑定到子组件 -->
<child-component ref="childComponentRef"></child-component>
<button @click="invokeChildMethod">Call Child Method</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
import ChildComponent from './path/to/ChildComponent.vue'
const childComponentRef = ref(null)
function invokeChildMethod(){
if (childComponentRef.value){
childComponentRef.value.childMethod()
}
}
</script>
上述代码展示了完整的流程:子组件公开了一个名为 childMethod
的函数供外界调用;而父组件则借助于 ref
创建了一条通往子组件的道路,并最终实现了对该方法的成功调用。
相关推荐


















