vue3通过ref获取子组件defineExpose的数据和方法

  1. 父组件:

    <script setup> import { defineAsyncComponent, watchEffect, toRefs, reactive } from 'vue';

    // 异步组件
    const Test = defineAsyncComponent(()=>import('./xx/Test.vue'))

    const child1Ref = ref(null)
    const state = reactive({
    age: 1,
    name: '2',
    sayHello: null,
    })
    watchEffect(() => {
    // 拿到子组件的一些数据
    console.log(child1Ref.value)
    const obj = toRefs(child1Ref.value)
    console.log(obj.a, obj.b)
    state.name = obj.b
    state.age = obj.a
    state.sayHello = obj.onSayHello
    })

    </script> <template> {{ state.age }} -- {{ state.name }} <button @click="state.sayHello">say hello</button> <Test ref="child1Ref"/> </template>
  2. 子组件

    <script setup> import { ref, defineExpose } from 'vue'

    const a = ref(101)
    const b = ref('sddewfewfew')

    const onSayHello = () => {
    console.log('hello')
    }
    defineExpose({
    a,
    b,
    onSayHello,
    })

    </script> <template>

    Child1

    </template>
相关推荐
北城以北88883 小时前
Vue-- Axios 交互(一)
前端·javascript·vue.js
shelutai3 小时前
实现提供了完整的 Flutter Web 文件上传解决方案
前端·flutter
gplitems1233 小时前
Spide - Personal Blog & Magazine WordPress Theme Download
javascript
im_AMBER3 小时前
Web 开发 29
前端·学习·web
前端开发爱好者3 小时前
Vite➕ 收费了!
前端·javascript·vue.js
gplitems1233 小时前
Petslist – Pet listing WordPress Theme Free Download
linux·服务器·前端
羊羊小栈3 小时前
基于「多模态大模型 + BGE向量检索增强RAG」的新能源汽车故障诊断智能问答系统(vue+flask+AI算法)
vue.js·人工智能·算法·flask·汽车·毕业设计·大作业
dcloud_jibinbin4 小时前
【uniapp】体验优化:开源工具集 uni-toolkit 发布
前端·webpack·性能优化·小程序·uni-app·vue
IT_陈寒4 小时前
Java性能调优实战:7个让GC效率提升50%的关键参数设置
前端·人工智能·后端
细节控菜鸡4 小时前
【2025最新】ArcGIS for JS 范围裁剪(只保留特定区域显示),实现精准地理范围聚焦
开发语言·javascript·arcgis