Skip to content

InstanceType 获取子组件实例

使用 InstanceType 可以获取子组件的实例类型,包括 defineExpose 暴露的属性和方法。

vue
<template>
  <child-component ref="child" />
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import childComponent from './child-component.vue';
const child = ref<InstanceType<typeof childComponent>>(null!);
child.value.func(); // "111"
console.log(child.value.a); // "1"
</script>
vue
<script lang="ts" setup>
function func() {
  console.log('111');
}

defineExpose({ func, a: '1' });
</script>