父组件
<template>
<div class="father">
<Son ref="Son"></Son>
<button @click="fnCallChild">
点我调用Son组件里的方法
</button>
</div>
</template>
<script setup>
import { ref } from "vue";
import Son from "../components/Son.vue";
const Son = ref(); //Son 要和Son组件上的class名相同
const fnCallChild = () => {
Son.value.sonFn(); //sonFn是子组件里的方法
};
</script>
子组件
<template>
<div>
<h1>{{ conts }}</h1>
</div>
</template>
<script setup>
import { ref } from 'vue';
/* 注意这里必须使用 defineExpose 把你想使用的方法导出去,
否则在父组件无法使用子组件的方法*/
defineExpose({
sonFn
})
const conts = ref('子组件')
function sonFn() {
conts.value = '父组件调用了子组件的方法'
}
</script>