main.ts 2.98 KB
import type { QiankunProps } from 'vite-plugin-qiankun/dist/helper';

import type { App as VueApp } from 'vue';

import { createApp } from 'vue';

import { createPinia } from 'pinia';
import {
  qiankunWindow,
  renderWithQiankun,
} from 'vite-plugin-qiankun/dist/helper';

import App from './App.vue';
import { createRouter } from './router';

import './style.css';

let app: null | VueApp<Element> = null;
let router: any = null;

/**
 * 渲染函数
 * @param props qiankun 传递的参数
 */
async function render(props: QiankunProps = {}) {
  const { container } = props;

  app = createApp(App);

  // 配置 Pinia
  app.use(createPinia());

  // 配置路由 - 根据是否在 qiankun 环境中使用不同的 base
  const routerBase = qiankunWindow.__POWERED_BY_QIANKUN__
    ? props.routerBase || '/subapp-vue'
    : '/';

  router = createRouter(routerBase);
  app.use(router);

  // 初始化通信管理器(仅在 qiankun 环境中)
  if (qiankunWindow.__POWERED_BY_QIANKUN__ && props.onGlobalStateChange) {
    const { subAppCommunication } = await import('./utils/communication');
    subAppCommunication.init(props);

    // 将通信管理器挂载到全局属性,方便组件使用
    app.config.globalProperties.$communication = subAppCommunication;
  }

  // 挂载应用
  const containerEl = container
    ? container.querySelector('#app')
    : document.querySelector('#app');

  if (containerEl) {
    app.mount(containerEl as Element);
  } else {
    console.error('[Vue3 微应用] 挂载容器未找到');
  }
}

/**
 * 独立运行时
 * 直接访问子应用时,不是通过基座加载
 */
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  console.log('独立运行模式');
  render();
}

/**
 * qiankun 生命周期钩子 - bootstrap
 * 只会在微应用初始化的时候调用一次,下次微应用重新进入时会直接调用 mount 钩子
 */
export async function bootstrap() {
  console.log('[Vue3 微应用] bootstrap');
}

/**
 * qiankun 生命周期钩子 - mount
 * 应用每次进入都会调用 mount 方法,通常在这里触发应用的渲染方法
 */
export async function mount(props: QiankunProps) {
  console.log('Vue3 微应用 mount', props);
  render(props);
}

/**
 * qiankun 生命周期钩子 - unmount
 * 应用每次切出/卸载都会调用 unmount 方法
 */
export async function unmount(props: QiankunProps) {
  console.log('[Vue3 微应用] unmount', props);

  // 销毁通信管理器
  if (qiankunWindow.__POWERED_BY_QIANKUN__) {
    const { subAppCommunication } = await import('./utils/communication');
    subAppCommunication.destroy();
  }

  if (app) {
    app.unmount();
    app = null;
  }
  if (router) {
    router = null;
  }
}

/**
 * qiankun 生命周期钩子 - update (可选)
 * 主应用向子应用下发新的props时触发
 */
export async function update(props: QiankunProps) {
  console.log('[Vue3 微应用] update', props);
}

// 使用 vite-plugin-qiankun 提供的渲染函数
renderWithQiankun({
  bootstrap,
  mount,
  unmount,
  update,
});