vue调用子组件的方法
时间: 2025-01-21 10:21:06 浏览: 17
实现 Vue 父组件调用子组件方法
在 Vue 3 的组合式 API 中,实现父组件调用子组件的方法涉及几个关键步骤。这些步骤确保了父子组件之间的有效通信。
子组件定义方法并暴露给外部使用
子组件需要定义一个方法,并通过 defineExpose
或者直接将其设置为可访问的状态以便于父组件能够调用它[^1]:
<script setup>
import { defineExpose } from 'vue'
function childMethod() {
console.log('This is a method of the child component.')
}
// Expose the function to parent components.
defineExpose({
childMethod,
})
</script>
<template>
<!-- Child Component Template -->
</template>
父组件引用子组件实例并通过其调用方法
父组件应当利用 <template>
创建子组件的同时为其分配一个 ref
属性来建立引用关系,在脚本部分则可以通过该引用去触发子组件内的特定函数[^2]:
<template>
<div>
<!-- Assigning reference "childRef" to the child component instance -->
<ChildComponent ref="childRef"></ChildComponent>
<button @click="invokeChildMethod">Invoke Child Method</button>
</div>
</template>
<script>
export default {
components: {
ChildComponent, // Assuming you have imported or registered your child component here
},
methods: {
invokeChildMethod(){
this.$refs.childRef.childMethod();
}
}
};
</script>
上述代码展示了如何配置子组件使其公开某个方法以及怎样让父组件获取到这个方法的执行权限。当点击按钮时,会激活 invokeChildMethod()
函数进而间接地使子组件里的 childMethod()
得以运行。
相关推荐

















