vue 使用 qiankun 微应用 两个或多个 子应用

乾坤文档链接:https://qiankun.umijs.org/zh/guide

  1. 安装乾坤 : yarn add qiankun # 或者 npm i qiankun --save

  2. 在 '@/qiankun/config.js' (主应用):

// 挂载的 子应用入口 
export default [
  {
    name: "auth1", //子应用名称
    entry: " http://localhost:8060", //子应用地址,假设此项目名称为智能质检应用(下面演示生命周期的时候会用到)
    container: "#childApp", //子应用要挂载的节点,和vue.$mount("#app")类似;
    activeRule: '/auth1' //重点:路由命中规则,当浏览器链接有#/quality时候,例如http://localhost:9000/#/quality/* ,就可以自动的把http://localhost:808挂载到本地的subapp-viewport节点下
  },
  {
    name: "auth2", //子应用名称
    entry: " http://localhost:8061", //子应用地址,假设此项目名称为智能质检应用(下面演示生命周期的时候会用到)
    container: "#childApp", //子应用要挂载的节点,和vue.$mount("#app")类似;
    activeRule: '/auth2' //重点:路由命中规则,当浏览器链接有#/quality时候,例如http://localhost:9000/#/quality/* ,就可以自动的把http://localhost:808挂载到本地的subapp-viewport节点下
  },
];
  1. 在 '@/qiankun/index.js' (主应用):
import microAppConfig from "./config"; //此文件代码在下方



import { registerMicroApps, initGlobalState } from "qiankun";


// //乾坤配置  https://qiankun.umijs.org/zh/api
export const qkConfig = {
  sandbox: { strictStyleIsolation: true } //开启shadow dom沙箱隔离
}
let actions: any = null;

/**registerMicroApps
 * @description:  添加监测状态
 */
function addState(state: any) {
  if (!actions) {
    /**
   * @description:  乾坤初始化全局监听状态
   * @param state要初始化的值
   */
    actions = initGlobalState(state);
    actions.onGlobalStateChange(
      (value: any, prev: any) => {
        console.log(`[主应用接收到值变化 - ${actions}]:`, value, prev);
      }
    );
  } else {
    /**
    * @description:  乾坤设置state值
    * @param state要更新的值
    */
    actions.setGlobalState(state);
  }
}

/**
 * @description:  注册子应用
 */
function registerApp() {

  /**
   * @description:  乾坤注册子应用
   * @param1 子应用配置
   * @param2 打开子应用时候触发的生命周期
   */
  registerMicroApps(microAppConfig, {
    beforeLoad: [
      function (app:any) :any {
        console.log("[主应用] before mount %c%s", "color: green;", app.name);
      }
    ],
    beforeMount: [
      function (app:any) :any{
        console.log("[主应用] before mount %c%s", "color: green;", app.name);
      }
    ],
    afterMount: [
      function (app:any) :any {
        console.log("[主应用] afterMount mount %c%s", "color: green;", app.name);
      }
    ],
    afterUnmount: [
      function (app:any) :any {
        console.log("[主应用] after unmount %c%s", "color: green;", app.name);
      }
    ]
  });
}

/**
 * @description:  挂载乾坤框架
 */
function setupQk(): void {
  const state = { a: 123 }
  registerApp()
  addState(state)
  /**
  * @description:  乾坤开启服务
  * @param1 全局配置
  */
}

export default setupQk;
  1. 在 'main.js' (主应用):
import setupQk from '@/qiankun/index'
// createApp(App).use(Antd).use(Vuei18n).use(store).use(router).mount("#app"); 
// 后面挂载qiankun
setupQk()
  1. 在 '@/views/qiankun.vue' (主应用):
// 挂载乾坤
import { qkConfig } from "@/qiankun/index"; import { start } from "qiankun"; // 在 Mounted dom挂载后 挂载乾坤 onMounted(() => { start(qkConfig); });
  1. 在 'main.js' (子应用 vue2.x ):
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import store from './store'
import routes from './router';

Vue.config.productionTip = false

let router = null;
let instance = null;

function render(props) {
  const { container } = props;
  router = new VueRouter({
    // base: window.__POWERED_BY_QIANKUN__ ? '/app1' : '/',
    mode: 'history',
    routes,
  });

  instance = new Vue({
    router,
    store,
    render: h => h(App),
  }).$mount(container ? container.querySelector('#app') : '#app');
}

if (!window.__POWERED_BY_QIANKUN__) {
  render();
}

export async function bootstrap() {
  console.log('vue app bootstraped');
}

export async function mount(props) {
  // console.log('挂载 vue2')
  render(props);
}

export async function unmount() {
  // console.log('卸载载 vue2')
  instance.$destroy();
  instance = null;
  router = null;
}
  1. 在 'main.js' (子应用 vue3.x ):
import { createApp } from 'vue'
import App from './App.vue'
import {routes} from './router'
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import store from './store'
console.log('routes' , routes)

let router: any = null;
let instance: any = null;

function render(props:any) {
  const { container } = props;

  router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
  })


  instance = createApp(App).use(store).use(router).mount(container != "" ? container.querySelector("#app") : '#app');
}


// 生命周期
export async function bootstrap() {
  console.log('[vue] vue app bootstraped');
}
export async function mount(props: any) {
  // console.log('挂载 vue1')
  let prop = {
    container:props.container
  }
  render(prop);
}
export async function unmount() {
  // console.log('卸载载 vue1')
  instance?.$destroy && instance.$destroy();
  instance = null;
  router = null;
}
  1. 在 'vue.config.js' (子应用 )解决访问子页面 跨域:
devServer: {
    port: 8080,
    headers: {          //  允许跨域访问子应用页面
      'Access-Control-Allow-Origin': '*',
    },
}

你可能感兴趣的:(vue 使用 qiankun 微应用 两个或多个 子应用)