概述
- 每個(gè)組件都可以作為插件,注冊(cè)到應(yīng)用上
- 在工具包中創(chuàng)建文件并定義兩個(gè)方法
makeInstaller
、withInstall
- makeInstaller:創(chuàng)建安裝器
- withInstall:設(shè)置組件為插件
import type { App, Plugin } from 'vue'
import { each } from 'lodash-es'
// 定義單文件組件為插件類型
// 即把單文件組件當(dāng)成是一個(gè)插件逆趋,可被安裝使用
type SFCWithInstall<T> = T & Plugin
// 把傳入的所有組件當(dāng)成插件進(jìn)行安裝
export function makeInstaller(components: Plugin[]) {
const install = (app: App) =>
each(components, (c) => {
app.use(c)
})
return install
}
// 將傳入的組件轉(zhuǎn)換成插件
// 即給組件添加install方法
// 當(dāng)使用app.use(component)時(shí)會(huì)自動(dòng)調(diào)用組件的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>
}