install.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { NOOP } from '@vue/shared'
  2. import type { App, Directive } from 'vue'
  3. import type { SFCInstallWithContext, SFCWithInstall } from './typescript'
  4. export const withInstall = <T, E extends Record<string, any>>(
  5. main: T,
  6. extra?: E
  7. ) => {
  8. ;(main as SFCWithInstall<T>).install = (app): void => {
  9. for (const comp of [main, ...Object.values(extra ?? {})]) {
  10. app.component(comp.name, comp)
  11. }
  12. }
  13. if (extra) {
  14. for (const [key, comp] of Object.entries(extra)) {
  15. ;(main as any)[key] = comp
  16. }
  17. }
  18. return main as SFCWithInstall<T> & E
  19. }
  20. export const withInstallFunction = <T>(fn: T, name: string) => {
  21. ;(fn as SFCWithInstall<T>).install = (app: App) => {
  22. ;(fn as SFCInstallWithContext<T>)._context = app._context
  23. app.config.globalProperties[name] = fn
  24. }
  25. return fn as SFCInstallWithContext<T>
  26. }
  27. export const withInstallDirective = <T extends Directive>(
  28. directive: T,
  29. name: string
  30. ) => {
  31. ;(directive as SFCWithInstall<T>).install = (app: App): void => {
  32. app.directive(name, directive)
  33. }
  34. return directive as SFCWithInstall<T>
  35. }
  36. export const withNoopInstall = <T>(component: T) => {
  37. ;(component as SFCWithInstall<T>).install = NOOP
  38. return component as SFCWithInstall<T>
  39. }