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>
相关推荐
lizhongxuan6 小时前
Claude Code 防上下文爆炸:源码级深度解析
前端·后端
天真萌泪7 小时前
JS逆向自用
开发语言·javascript·ecmascript
柳杉7 小时前
震惊!字符串还能这么玩!
前端·javascript
是上好佳佳佳呀8 小时前
【前端(五)】CSS 知识梳理:浮动与定位
前端·css
仍然.8 小时前
算法题目---模拟
java·javascript·算法
wefly20178 小时前
纯前端架构深度解析:jsontop.cn,JSON 格式化与全栈开发效率平台
java·前端·python·架构·正则表达式·json·php
我命由我1234510 小时前
React - 类组件 setState 的 2 种写法、LazyLoad、useState
前端·javascript·react.js·html·ecmascript·html5·js
聊聊MES那点事10 小时前
JavaScript图表控件AG Charts使用教程:使用AG Charts React实时更新柱状图
开发语言·javascript·react.js·图表控件
自由生长202410 小时前
IndexedDB的观察
前端
IT_陈寒11 小时前
Vite热更新坑了我三天,原来配置要这么写
前端·人工智能·后端