自动导入组件时的ref类型引用

159 阅读1分钟

unplugin-vue-components 使用中的一个小补丁

//新建 ComponentInstance.d.ts
// unplugin-vue-components v0.25.1 之前的版本使用 @vue/runtime-core
import { GlobalComponents } from 'vue'

declare global {
    type ComponentInstance = {
      //ComponentExposed 可以用 InstanceType替换
        [Property in keyof GlobalComponents]: ComponentExposed<GlobalComponents[Property]>
    }
    type ComponentExposed<T> =
        T extends new () => infer E ? E :
        T extends (props: any, ctx: any, expose: (exposed: infer E) => any, ...args: any) => any ? NonNullable<E> :
        any;
}

在vue页面中使用

/**
* vue文件中使用
**/
const listRef = ref<ComponentInstance['HikList']>();

当然,如果使用vue@3.5 以上版本 useTemplateRef 语法糖会帮我们解决子组件的类型问题 强烈建议升级!

image.png