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>
相关推荐
很晚很晚了1 小时前
纯前端转全栈 Day 1:我从第一个 NestJS 接口开始
前端
Lee川2 小时前
从零解剖一个 AI Agent Tool是如何实现的
前端·人工智能·后端
wangruofeng3 小时前
Playwright 深度调研:为什么它成了浏览器自动化的新底座
前端·测试
李白的天不白5 小时前
SSR服务端渲染
前端
XinZong5 小时前
OpenClaw 实现「龙虾」vs 龙虾 vs 用户 ws对话实现方案 + 实际落地项目
javascript
卷帘依旧6 小时前
WebSocket 比 SSE 复杂在哪里
javascript
卷帘依旧6 小时前
SSE(Server-Sent Events)完全指南
前端
码云之上6 小时前
万星入坞:我们如何用三层插件体系干掉巨石应用
前端·架构·前端框架
kyriewen6 小时前
一口气讲清楚 Monorepo、Turborepo、pnpm、Changesets 到底是什么?
前端·架构·前端工程化
logo_287 小时前
Xpath语法规则的学习和使用
javascript·python·xpath·xpath语法