Vue script setup 父组件调用子组件方法
Vue版本 3.2.31
1、先在父组件的模板中,调用子组件的地方定义ref,来确认是要调用哪个子组件里面的方法。
2、在子组件中定义一个要调用的方式,然后defineExpose({xxxxxxxxx}),暴露出去给父组件用。
3、在父组件中ref.value.xxxxxxxxx();就能直接调用子组件的方法了。
<template>
<div class="parent">
<button @click="CallChildFunc">触发子组件方法</button>
<!-- 1. 定义ref -->
<child ref="childRef"></child>
</div>
</template>
<script setup>
import {ref } from "vue";
import child from "@/components/child.vue";
// 1. 定义与ref同名变量
const childRef = ref(null);
const CallChildFunc= () => {
// 3.直接调用子组件方法。
childRef.value.test(args1,args2);
}
</script>
//子组件
<template>
<div class="child"></div>
</template>
<script setup>
const test = (a,b) => {
console.log('已触发组件方法',a,b);
}
//2.把方法暴露给父组件
defineExpose({test})
</script>