如何在Vue组合式API中从父组件调用子组件方法?
Vue3(组合式API/选项式API)父组件调用子组件方法的实现
在Vue3中,父组件调用子组件方法的核心逻辑依然是通过ref绑定子组件实例,但在最常用的<script setup>语法中需要额外处理方法暴露,以下分两种场景说明:
一、使用<script setup>(组合式API常用写法)
<script setup>默认会封闭组件内部的属性和方法,必须通过defineExpose主动暴露需要外部访问的方法,才能让父组件调用。
1. 子组件代码
<template> <div>子组件区域</div> </template> <script setup> // 定义子组件的方法 const childMethod = () => { console.log('子组件方法被父组件调用了') } // 暴露方法给父组件 defineExpose({ childMethod }) </script>
2. 父组件代码
通过ref创建变量绑定子组件,在合适的时机(如生命周期、用户事件)调用子组件方法:
<template> <!-- 绑定ref到子组件 --> <MyComponent ref="childComponentRef" /> <!-- 可选:通过按钮触发调用 --> <button @click="invokeChildMethod">调用子组件方法</button> </template> <script setup> import { ref, onMounted } from 'vue' import MyComponent from './MyComponent.vue' // 创建ref实例,用于绑定子组件 const childComponentRef = ref(null) // 定义调用子组件方法的函数 const invokeChildMethod = () => { // 先判断子组件实例是否存在,避免报错 if (childComponentRef.value) { childComponentRef.value.childMethod() } } // 在组件挂载完成后调用 onMounted(() => { invokeChildMethod() }) </script>
二、使用Vue3选项式API
如果在Vue3中依然使用选项式API,写法和Vue2基本一致,直接通过this.$refs访问子组件实例并调用方法:
父组件代码
<template> <MyComponent ref="childComponent" /> </template> <script> import MyComponent from './MyComponent.vue' export default { components: { MyComponent }, mounted() { // 直接通过$refs访问子组件并调用方法 this.$refs.childComponent.childMethod() } } </script>
子组件代码(选项式API)
<template> <div>子组件区域</div> </template> <script> export default { methods: { childMethod() { console.log('子组件方法被父组件调用了') } } } </script>
内容的提问来源于stack exchange,提问作者Mohammad Javad Khademian
相关产品推荐
相关产品推荐

