在使用子组件的引入时,有时需要获取子组件实例并调用子组件的方法或者属性,
下面举一个例子:
子组件部分代码如下
<script setup lang="ts">
import * as echarts from 'echarts';
import type { ECharts } from 'echarts';
import { shallowRef, ref, onMounted, onBeforeUnmount } from 'vue';
const prop = defineProps<{
option: echarts.EChartsCoreOption,
width?: string,
height?: string,
}>()
const chartsEl = ref<HTMLElement>();
const Chart = shallowRef<ECharts>();
const chartInit = (El: HTMLElement) => {
return echarts.init(El);
};
const ChartReset = (option: echarts.EChartsCoreOption) => {
Chart.value?.clear()
Chart.value?.setOption(option);
}
//使用defineExpose暴露子组件的方法属性
defineExpose({
Chart,
ChartReset
})
onMounted(()=>{
chartsEl?.value && Chart = chartInit(chartsEl.value)
})
</script>
<template>
<div class="chartbox" :style="{ width: width, height: height }">
<div class="chart" ref="chartsEl"></div>
</div>
</template>
父组件引入
<script setup lang="ts">
import MyChart from '@/components/MyEcharts/MyEcharts.vue';
import { ref } from 'vue';
import { BaseBarOptions } from '@/components/MyEcharts/MyEchartsOptions';
const EchartEl = ref<InstanceType<typeof MyChart>>()
EchartEl.value?.
</script>
<template>
<MyChart :option={BaseBarOptions} ref="EchartEl"/>
</template>
<style>
</style>
再次使用已经可见子组件暴露的方法属性的类型提示:
typeof MyChart
其中typeof
是 TypeScript 中的一种操作符,用于获取一个变量或表达式的类型。
在这里表示获取myChart
构造函数的类型并传递给InstanceType
这是InstanceType
的详细代码:
type InstanceType<T extends abstract new (...args: any) => any> = T extends abstract new (...args: any) => infer R ? R : any;
关于InstanceType
的解析一步一步的解释:
type
:这个关键字声明了一个类型别名。InstanceType
:这是这个类型起的名字。<T extends abstract new (...args: any) => any>
:这部分定义了一个泛型类型 T,它必须是一个构造函数的类型。extends abstract new (...args: any) => any
表示 T 必须是一个构造函数类型,其中 abstract new 表示这是一个抽象类的构造函数类型。T extends abstract new (...args: any) => infer R
:这部分使用了条件类型。它的意思是,如果 T 是一个抽象类的构造函数类型,那么就把构造函数的实例类型提取出来,保存到 R 中。infer 关键字用于推断类型,这里是推断构造函数的实例类型。? R : any
:这是条件运算符 ? : 的一部分。如果前面的条件成立,即 T 是一个抽象类的构造函数类型,那么返回 R,也就是构造函数的实例类型;否则返回 any,表示任何类型。InstanceType<T>
是一个泛型类型,用于从抽象类的构造函数类型 T 中提取构造函数的实例类型。
如果这篇文章对您有所帮助,还望点赞关注收藏三连!!,后续更新更多内容