全局注册组件
1.新建文件components/index.ts
import type { App, Plugin } from 'vue' //这里的是插件的类型
import Skeleton from './Skeleton/Skeleton.vue'
const UserUI: Plugin = {
install(app: App) {
// 全局注册组件
app.component(`XtxSkeleton`, Skeleton);
},
};
export default UserUI;
2.在main.ts
中全局注册
3.在页面中使用
-
🐛问题:全局组件注册成功,但是调用时没有 TS 类型提示。
-
解决方案:为组件库创建对应的类型声明文件。
参考链接:https://github.com/element-plus/element-plus/blob/dev/global.d.ts
https://github.com/johnsoncodehk/volar/blob/master/extensions/vscode-vue-language-features/README.md
需要在公共组件库下创建一个专门用于类型声明文件global.d.ts
// 全局组件类型声明文件 for Volar
declare module 'vue' {
// 全局组件需要定义 interface GlobalComponents
//volar内部通过GlobalComponents 接口去进行类型处理的
export interface GlobalComponents {
全局组件名: 组件类型;
}
}
export { }
注意:需要导入 .vue 源文件 typeof 指定类型