概述
- 每个组件都可以作为插件,注册到应用上
- 在工具包中创建文件并定义两个方法
makeInstaller
、withInstall
- makeInstaller:创建安装器
- withInstall:设置组件为插件
import type { App, Plugin } from 'vue'
import { each } from 'lodash-es'
type SFCWithInstall<T> = T & Plugin
export function makeInstaller(components: Plugin[]) {
const install = (app: App) =>
each(components, (c) => {
app.use(c)
})
return install
}
export const withInstall = <T>(component: T) => {
;(component as SFCWithInstall<T>).install = (app: App) => {
const name = (component as any)?.name || 'UnnamedComponent'
app.component(name, component as SFCWithInstall<T>)
}
return component as SFCWithInstall<T>
}