vue3父组件获取子组件实例(2024-06-22)

vue3获取子组件实例

在Vue 3中,可以使用ref来获取子组件的实例。首先,在父组件中需要引入ref,然后在模板中通过ref属性为子组件设置一个引用名称。之后,可以在父组件的setup函数中使用refAPI来访问子组件实例。

以下是一个简单的例子:

<!-- 父组件 -->
<template>
  <ChildComponent ref="child" />
</template>
 
<script setup>
import { ref, onMounted } from 'vue';
import ChildComponent from './ChildComponent.vue';
 
const child = ref(null);
 
onMounted(() => {
  // 子组件实例可以通过 child.value 访问
  console.log(child.value.getData());
});
</script>
<!-- 子组件 -->
<template>
  <div>我是子组件</div>
</template>
 
<script setup>
// 子组件的逻辑
function getData(){

}
//这里需要暴露出去不然父组件调用不到这个数据
defineExpose({ getData })

</script>

在这个例子中,ChildComponent是子组件,在父组件中通过

<ChildComponent ref="child" />

为其设置了一个引用。在父组件的setup函数中,通过

const child = ref(null);

声明了一个ref,并将其赋值给child

onMounted生命周期钩子中,可以通过child.value访问到子组件的实例。

猜你喜欢

转载自blog.csdn.net/hap1994/article/details/139874086