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>
<p>Child1</p>
</template>