vue3通过ref获取子组件defineExpose的数据和方法

27 篇文章 1 订阅
2 篇文章 0 订阅

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>

如果父组件引用了组件但没有在模板中创建组件的标签,你无法直接调用组件中通过`defineExpose`暴露的方法。这是因为在Vue 3中,`defineExpose`只能被父组件模板中的组件访问。 如果你想在父组件中调用组件方法,一种可行的方式是使用`ref`来获取组件实例,并通过`.value`来访问组件方法。以下是一个示例: 在父组件中,使用`ref`来创建对组件实例的引用: ```vue <template> <div> <!-- 不创建组件标签 --> <button @click="callChildMethod">调用组件方法</button> </div> </template> <script> import { ref } from 'vue'; import ChildComponent from './ChildComponent.vue'; export default { setup() { const childComponentRef = ref(null); const callChildMethod = () => { // 检查组件实例是否存在 if (childComponentRef.value) { childComponentRef.value.childMethod(); } }; return { callChildMethod, childComponentRef }; }, components: { ChildComponent } }; </script> ``` 在组件中,通过`defineExpose`暴露需要调用的方法: ```vue <template> <!-- 组件模板内容 --> </template> <script> import { defineComponent, defineExpose } from 'vue'; export default defineComponent({ setup() { const childMethod = () => { // 组件方法逻辑 }; defineExpose({ childMethod }); // 其他组件逻辑 return {}; } }); </script> ``` 在父组件中,通过 `childComponentRef.value.childMethod()` 来调用组件中的 `childMethod` 方法。确保在调用组件方法之前,检查组件实例是否存在。这样即使没有创建组件标签,也可以调用组件中通过`defineExpose`暴露的方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值