父组件示例
<template>
  <div class="container">
      <h-demo ref="childDom" />
 
      <button @click="getChild"></button>
  </div>
</template>
 
<script setup>
import Hdemo from '@/components/Hdemo';
import { ref, } from 'vue';
const childDom=ref(null)
 
 
onMounted(() => {
  const getChild = () =>{
    console.log(childDom.value)
    // 打印当前子组件暴露出来的数据
    childDom.value.handleVal()
    // 执行子组件方法
  }
})
</script>
<style lang="scss" scoped>
 
</style>
 
子组件使用defineExpose 暴露示例
 
 
<script setup>
import { ref } from 'vue';
    const demo=ref('测试用例')
    const  handleVal=()=>{
        demo.value="已改变"
    }
//将需要暴露出去的数据与方法都可以暴露出去
    defineExpose({
        demo,
        handleVal,
    })
</script>
<template>
  <div class="inner">
      {{demo}}
      <button @click="handleVal">改值</button>
  </div>
</template>
<style lang="scss" scoped>
 
</style>
 
此时父组件即可获取子组件内部变量与方法与当前dom等信息,父组件必须在onMounted钩子函数中才能访问到ref中的值。




















