vue.ts 993 B

12345678910111213141516171819202122232425262728293031323334
  1. import { Plugin, inject } from "vue"
  2. import { Container } from "./container"
  3. import { Service } from "./service"
  4. const VUE_CONTAINER_KEY = Symbol()
  5. // TODO: Some Vue version issue with plugin generics is breaking type checking
  6. /**
  7. * The Vue Dioc Plugin, this allows the composables to work and access the container
  8. *
  9. * NOTE: Make sure you add `vue` as dependency to be able to use this plugin (duh)
  10. */
  11. export const diocPlugin: Plugin = {
  12. install(app, { container }) {
  13. app.provide(VUE_CONTAINER_KEY, container)
  14. }
  15. }
  16. /**
  17. * A composable that binds a service to a Vue Component
  18. *
  19. * @param service The class reference of the service to bind
  20. */
  21. export function useService<
  22. T extends typeof Service<any> & { ID: string }
  23. >(service: T): InstanceType<T> {
  24. const container = inject(VUE_CONTAINER_KEY) as Container | undefined | null
  25. if (!container) {
  26. throw new Error("Container not found, did you forget to install the dioc plugin?")
  27. }
  28. return container.bind(service)
  29. }