wujie框架实战

173 阅读2分钟

wujie是一个基于Web Component容器+iframe沙箱的微前端框架,可以多个应用独立发布功能来共同构建现代化web应用。

与single-spa、qiankun

等方案的区别:single-spa通过监听路由的变化,匹配到激活的路由加载子应用资源,而wujie可以同时激活多个子应用页面,子应用采用iframe路由,不用关心路由占用问题。因此,适用与一些web操作系统的应用中。

快速上手

主应用

在主应用安装wujie

pnpm add wujie wujie-vue2

设置子应用

import WujieVue from "wujie-vue2";
const { setupApp, preloadApp, bus } = WujieVue;
setupApp({
  name: "vue2",
  url: "//localhost:7200/",
  exec: true
});

嵌入子应用

创建vue页面用于承载子应用,如main-vue/src/views/Vue2.vue

<template>
    <!--单例模式,name相同则复用一个无界实例,改变url则子应用重新渲染实例到对应路由 -->
    <WujieVue width="100%" height="100%" name="vue2" :url="vue2Url" :sync="true"></WujieVue>
</template>
  

配置子应用路由

import VueRouter from "vue-router";
import Vue2 from "../views/Vue2.vue";

const router = new VueRouter({
  mode: "history",
  base: basename,
  routes:[
  {
    path: "/vue2",
    name: "vue2",
    component: Vue2,
  }
  ],
});

子应用

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

// new Vue({
//   render: h => h(App),
// }).$mount('#app')

if (window.__POWERED_BY_WUJIE__) {
  let instance;
  window.__WUJIE_MOUNT = () => {
    instance = new Vue({ render: (h) => h(App) }).$mount("#app");
  };
  window.__WUJIE_UNMOUNT = () => {
    instance.$destroy();
  };
} else {
  new Vue({ render: (h) => h(App) }).$mount("#app");
}

如何子应用的实例化是在异步函数中进行的,在定义完生命周期函数后,需要主动调用wujie的渲染函数window.__WUJIE.mount()

应用间通信

1.props通信

主应用可以通过props注入数据和方法:

<WujieVue name="xxx" url="xxx" :props="{ data: xxx, methods: xxx }"></WujieVue>

子应用可以通过$wujie来获取:

const props = window.$wujie?.props; // {data: xxx, methods: xxx}

2.window通信

由于子应用运行的iframe的src和主应用是同域的,所以相互之间可以直接通信

主应用调用子应用的全局数据

window.document.querySelector("iframe[name=子应用id]").contentWindow.xxx;

子应用调用主应用的全局数据:

window.parent.xxx;

3.eventBus通信:

// 如果使用wujie
import { bus } from "wujie";

// 如果使用wujie-vue
import WujieVue from "wujie-vue";
const { bus } = WujieVue;

// 如果使用wujie-react
import WujieReact from "wujie-react";
const { bus } = WujieReact;

// 主应用监听事件
bus.$on("事件名字", function (arg1, arg2, ...) {});
// 主应用发送事件
bus.$emit("事件名字", arg1, arg2, ...);
// 主应用取消事件监听
bus.$off("事件名字", function (arg1, arg2, ...) {});

// 子应用监听事件
window.$wujie?.bus.$on("事件名字", function (arg1, arg2, ...) {});
// 子应用发送事件
window.$wujie?.bus.$emit("事件名字", arg1, arg2, ...);
// 子应用取消事件监听
window.$wujie?.bus.$off("事件名字", function (arg1, arg2, ...) {});