index.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { ComponentPublicInstance, StyleValue, createApp } from 'vue';
  2. import main from './main.vue';
  3. const initInstance = (option: IOption) => {
  4. // 这里就是与vue2最大的区别了,在vue2的时候,我们只需instance.$mount()便能得到节点,现在不行
  5. const app = createApp(main);
  6. const container = document.createElement('div');
  7. // @ts-ignore
  8. const instance: ComponentPublicInstance<InstanceType<typeof main>> =
  9. app.mount(container);
  10. if (option.el) {
  11. instance.isFixed = false;
  12. option.el.appendChild(container);
  13. } else {
  14. instance.isFixed = true;
  15. document.body.appendChild(container);
  16. }
  17. return instance;
  18. };
  19. interface IOption {
  20. content?: string;
  21. style?: StyleValue;
  22. loading?: boolean;
  23. showMask?: boolean;
  24. el?: HTMLElement;
  25. }
  26. const defaultOption: IOption = {
  27. content: '',
  28. showMask: false,
  29. style: {},
  30. };
  31. let globalLoading;
  32. // 直接导出该方法
  33. export const fullLoading = function (option: IOption): IOption {
  34. const newOption = {
  35. ...defaultOption,
  36. ...option,
  37. };
  38. // 没有传el,代表是全局的loading,全局loading的话就使用单例
  39. if (!newOption.el) {
  40. if (!globalLoading) {
  41. globalLoading = initInstance(newOption);
  42. }
  43. Object.keys(newOption).forEach((key) => {
  44. globalLoading[key] = option?.[key] || newOption[key];
  45. });
  46. return globalLoading;
  47. } else {
  48. const cptLoading = initInstance(newOption);
  49. Object.keys(newOption).forEach((key) => {
  50. cptLoading[key] = option?.[key] || newOption[key];
  51. });
  52. return cptLoading;
  53. }
  54. };
  55. // 不推荐。
  56. // export const usefullLoading = {
  57. // install: (app: App) => {
  58. // // 挂载在根实例的全局配置上
  59. // app.config.globalProperties['$fullLoading'] = fullLoading;
  60. // },
  61. // };