注意:请确保子组件已经正确挂载,并且通过 defineExpose
暴露了您想要在父组件中访问的属性或方法
parent.vue
<template>
<child ref="childRef"></child>
<button @click="fun">点击父组件</button>
</template>
<script setup lang="ts">
import { ref } from "vue"
import child from "./child.vue"
const childRef = ref(undefined as {
childFun: () => void,
childFunVue2: () => void
} | undefined)
const fun = () => {
console.log("fun==",childRef.value)
// console.log(childRef.value)
// childRef.value?.childFunVue2()
}
</script>
child.vue
<template>
<div>
<button>这里是子组件</button>
<!-- <slot name="child1"/>-->
<!-- <slot name="child2"/>-->
</div>
</template>
<script setup lang="ts">
import {defineExpose} from "vue"
const childFun = () => {
console.log("这里是子组件的方法")
}
const childFunVue2 = () => {
console.log("这里是子组件的方法Vue2")
}
defineExpose({
childFun,
childFunVue2
})
</script>