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>
相关推荐
(((φ(◎ロ◎;)φ)))牵丝戏安3 分钟前
根据输入的数据渲染柱形图
前端·css·css3·js
wuyijysx15 分钟前
JavaScript grammar
前端·javascript
溪饱鱼36 分钟前
第6章: SEO与交互指标
服务器·前端·microsoft
咔_1 小时前
LinkedList详解(源码分析)
前端
逍遥德1 小时前
CSS可以继承的样式汇总
前端·css·ui
读心悦1 小时前
CSS3 选择器完全指南:从基础到高级的元素定位技术
前端·css·css3
大鱼前端2 小时前
Vue 3.5 :新特性全解析与开发实践指南
vue.js
学渣y2 小时前
React状态管理-对state进行保留和重置
javascript·react.js·ecmascript
_龙衣3 小时前
将 swagger 接口导入 apifox 查看及调试
前端·javascript·css·vue.js·css3
进取星辰3 小时前
25、Tailwind:魔法速记术——React 19 样式新思路
前端·react.js·前端框架