1.父组件通过ref注册子组件
<template>
<div>
<Son :name='myName' ref="hello"/>
</div>
</template>
<script setup lang="ts">
import {onMounted,onBeforeMount,onBeforeUnmount,onUnmounted,ref,watch,computed} from 'vue'
import Son from '@/components/Son.vue'
// 声明子组件ref
const hello = ref<any>(null)
onMounted(() => {
// ref属性的调用 要想访问子组件的属性方法 子组件需要暴露出去
console.log('ref的dom', hello.value.age) // ref的dom节点
})
</script>
2.子组件需要将自己可以被父组件访问到的属性方法暴露出去
<script setup lang="ts">
const name2 = (getCurrentInstance()?.parent as any)?.devtoolsRawSetupState
const age = ref<number>(18)
const changeAge = (val:number) => {
age.value = val
}
// 子组件暴露给外部组件的属性or方法
defineExpose({
name2,
age,
changeAge
});
</script>