一、父组件调用子组件方法
下面演示为使用 setup 语法糖的情况,值得注意的是子组件需要使用 defineExpose 对外暴露方法,父组件才可以调用!
1、子组件
<template>
</template><script setup lang="ts">
// 第一步:定义子组件里面的方法
const doSth = (str: string) => {
console.log("子组件的 doSth 方法执行了!" + str);
}
// 第二步:暴露方法
defineExpose({ doSth })
</script><style scoped>
</style>
2、父组件
<template> <button @click="getChild">触发子组件方法</button> <!-- 第一步:定义 ref --> <HelloWorld ref="childRef" /> </template> <script setup lang="ts"> // 一、导入 import { ref } from 'vue'; import HelloWorld from './components/HelloWorld.vue'; // 二、数据 // 第二步:定义与 ref 同名变量 const childRef = ref<any>(); // 三、函数 const getChild = () => { // 第三步: 调用子组件的方法或者变量,通过value childRef.value.doSth("longchengdashabi"); } </script> <style> </style>