mountComponent.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { createApp, Component } from 'vue';
  2. import { isFunction, isString } from '../util';
  3. export const CreateComponent = (options: any, component: any) => {
  4. let elWarp: HTMLElement = document.body;
  5. const teleport = (options.teleport as string) || 'body';
  6. if (teleport != 'body') {
  7. if (isString(teleport)) {
  8. elWarp = document.querySelector(teleport) as HTMLElement;
  9. } else {
  10. elWarp = options.teleport as HTMLElement;
  11. }
  12. }
  13. const root = document.createElement('view');
  14. const name = component.name ? component.name + '-' : '';
  15. const id1 = options.id || new Date().getTime();
  16. root.id = name + id1;
  17. let Wrapper = {};
  18. if (isFunction(component.wrapper)) {
  19. Wrapper = component.wrapper(elWarp, root);
  20. } else {
  21. Wrapper = component.wrapper;
  22. }
  23. const instance: Component = createApp(Wrapper, options);
  24. const componens = component.components;
  25. componens &&
  26. componens.forEach((comp: Component) => {
  27. instance.use(comp);
  28. });
  29. elWarp.appendChild(root);
  30. return {
  31. instance: instance.mount(root),
  32. unmount: () => {
  33. instance.unmount();
  34. elWarp.removeChild(root);
  35. }
  36. };
  37. };