vue3父组件调用子组件方法的大坑

复制粘贴能跑就行 / 2024-10-11 / 原文

父组件:
<template>
  <ChildComponent ref="callChildMethod" />
</template>
 
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
 
const callChildMethod = ref();
 
// 可以在任何适当的时机调用子组件的方法
function parentMethod() {
  if (callChildMethod.value) {
    callChildMethod.value.childMethod();
  }
}
</script>

子组件

<template>
  <div>子组件内容</div>
</template>
 
<script setup>
import { defineExpose } from 'vue';//要被父组件调用的方法不能这样定义
const childMethod = ()=>{
    console.log('子组件方法被调用');
}
function childMethod() {
  console.log('子组件方法被调用');
}
//注意这点要暴露出去
defineExpose ({
    childMethod
})
</script>