30.a-Vue use 源码手写
小于 1 分钟
myUse.ts
import type { App } from 'vue'
import { app } from './main' //./main.ts 导出app export const app = createApp(App)
interface Use {
install: (app: App, ...options: any[]) => void
}
const installedList = new Set()
export function MyUse<T extends Use>(plugin: T, ...options: any[]) {
if(installedList.has(plugin)){
return console.warn('重复添加插件',plugin)
}else{
plugin.install(app, ...options)
installedList.add(plugin)
}
}
源码展示
use(plugin, ...options) {
if (installedPlugins.has(plugin)) ;
else if (plugin && shared.isFunction(plugin.install)) {
installedPlugins.add(plugin);
plugin.install(app, ...options);
}
else if (shared.isFunction(plugin)) {
installedPlugins.add(plugin);
plugin(app, ...options);
}
else ;
return app; //支持链式调用
},