vue3 父元素调子元素方法
时间: 2025-03-08 16:06:30 浏览: 11
实现 Vue 3 父组件调用子组件方法
使用组合式 API (Composition API)
在子组件中定义并暴露所需的方法:
// ChildComponent.vue
<template>
<!-- 子组件模板 -->
</template>
<script setup>
import { ref, defineExpose } from 'vue'
const childMethod = () => {
console.log('Child method called')
}
defineExpose({
childMethod
})
</script>
父组件通过 ref
创建引用,并利用该引用来调用子组件中的公开方法[^1]。
<!-- ParentComponent.vue -->
<template>
<div>
<child-component ref="childRef"></child-component>
<button @click="callChildMethod">Call Child Method</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'
const childRef = ref(null)
const callChildMethod = () => {
if (childRef.value && typeof childRef.value.childMethod === 'function') {
childRef.value.childMethod()
}
}
</script>
对于选项式 API (Options API),过程相似,主要区别在于语法结构不同。子组件同样需要声明要暴露出去的内容,在此情况下通常是在 mounted()
钩子里设置 $refs
或者直接返回想要共享的对象/函数[^2]。
// Option API 版本的子组件
export default {
mounted() {
this.$emit('exposed', { childMethod: this.someLocalMethod })
},
methods: {
someLocalMethod() {
alert('Option API method invoked!')
}
}
}
而父组件则监听来自子组件的事件以获取其提供的接口。
<!-- Options API 的父组件 -->
<template>
<div>
<child-component v-on:exposed="(methods) => exposedMethods = methods">
</child-component>
<button @click="invokeExposedMethod">Invoke Exposed Method</button>
</div>
</template>
<script>
export default {
data() {
return {
exposedMethods: null,
};
},
methods: {
invokeExposedMethod() {
if(this.exposedMethods?.someLocalMethod){
this.exposedMethods.someLocalMethod();
}
}
}
};
</script>
上述两种方式均能有效地让父级访问到子级的功能逻辑,具体选用哪种取决于项目的技术栈偏好以及团队开发习惯等因素。
相关推荐















