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>
相关推荐
qq_2081540885几秒前
瑞树6代流程分析
javascript·python
UXbot3 分钟前
AI原型设计工具评测:从创意到交互式Demo,5款产品全面解析
前端·ui·设计模式·ai·ai编程·原型模式
落魄江湖行4 分钟前
硅基同事埋的坑,我用2小时才填平:Nuxt 4 路由踩坑:可选参数 [[id]] 与 [id] 的区别
前端
一勺菠萝丶10 分钟前
管理后台使用手册在线预览与首次登录引导弹窗实现
java·前端·数据库
军军君0110 分钟前
Three.js基础功能学习十四:智能黑板实现实例一
前端·javascript·css·typescript·前端框架·threejs·智能黑板
小村儿13 分钟前
连载05-Claude Skill 不是抄模板:真正管用的 Skill,都是从实战里提炼出来的
前端·后端·ai编程
xiaotao13119 分钟前
JS new 操作符完整执行过程
开发语言·前端·javascript·原型模式
robch25 分钟前
python3 -m http.server 8001直接启动web服务类似 nginx
前端·nginx·http
吴声子夜歌32 分钟前
ES6——数组的扩展详解
前端·javascript·es6
guhy fighting41 分钟前
new Map,Array.from,Object.entries的作用以及使用方法
开发语言·前端·javascript