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>
相关推荐
wearegogog1236 小时前
基于 MATLAB 的卡尔曼滤波器实现,用于消除噪声并估算信号
前端·算法·matlab
Drawing stars6 小时前
JAVA后端 前端 大模型应用 学习路线
java·前端·学习
品克缤6 小时前
Element UI MessageBox 增加第三个按钮(DOM Hack 方案)
前端·javascript·vue.js
小二·7 小时前
Python Web 开发进阶实战:性能压测与调优 —— Locust + Prometheus + Grafana 构建高并发可观测系统
前端·python·prometheus
小沐°7 小时前
vue-设置不同环境的打包和运行
前端·javascript·vue.js
Irene19917 小时前
Vue3 <Suspense> 使用指南与注意事项
vue.js·suspense
qq_419854057 小时前
CSS动效
前端·javascript·css
烛阴7 小时前
3D字体TextGeometry
前端·webgl·three.js
桜吹雪8 小时前
markstream-vue实战踩坑笔记
前端
南村群童欺我老无力.8 小时前
Flutter应用鸿蒙迁移实战:性能优化与渐进式迁移指南
javascript·flutter·ci/cd·华为·性能优化·typescript·harmonyos