微前端 micro-app 传参、通信
微前端 micro-app 传参、通信
环境及配置,参考:https://www.cnblogs.com/1285026182YUAN/p/17828681.html
主应用
<template> <div class="container" style="margin: 40px">
页面其他内容
<a-button type="primary" @click="fun_send_to_son">发送数据</a-button> <micro-app name="my-app-page1" url="http://localhost:5173/stand" :data="microAppData" @created="handleCreate" @beforemount="handleBeforeMount" @mounted="handleMount" @unmount="handleUnmount" @error="handleError" @datachange="handleDataChange" disableSandbox inline ></micro-app> </div> </template> <script> import { EventCenterForMicroApp } from '@micro-zoe/micro-app'; // 因为vite子应用关闭了沙箱,我们需要为子应用appname-vite创建EventCenterForMicroApp对象来实现数据通信 window.eventCenterForAppNameVite = new EventCenterForMicroApp('my-app-page1'); export default { data() { return { microAppData: { msg: '来自基座的数据' }, }; }, methods: { fun_send_to_son() { this.microAppData = { msg: '来自基座的实时数据' + Math.random() }; }, handleCreate() { console.log('child-vite 创建了'); }, handleBeforeMount() { console.log('child-vite 即将被渲染'); }, handleMount() { console.log('child-vite 已经渲染完成'); }, handleUnmount() { console.log('child-vite 卸载了'); }, handleError() { console.log('child-vite 加载出错了'); }, handleDataChange(e) { console.log('来自子应用 child-vite 的数据:', e.detail.data); }, }, }; </script> <style lang="less" scoped> .container { position: absolute; height: 100%; width: 100%; } </style>
子应用
创建通信组件 src / utils / MicroTidings.ts
import { Router } from "vue-router";
declare global {
interface Window {
eventCenterForAppNameVite: any;
__MICRO_APP_NAME__: string;
__MICRO_APP_ENVIRONMENT__: string;
__MICRO_APP_BASE_APPLICATION__: string;
}
}
// 与基座进行数据交互
export function handleMicroData(router: Router) {
// eventCenterForAppNameVite 是基座添加到window的数据通信对象
if (window.eventCenterForAppNameVite) {
// 主动获取基座下发的数据
console.log(
"child-vite getData:",
window.eventCenterForAppNameVite.getData()
);
// 监听基座下发的数据变化
window.eventCenterForAppNameVite.addDataListener(
(data: Record<string, unknown>) => {
console.log("child-vite addDataListener:", data);
if (data.path && typeof data.path === "string") {
data.path = data.path.replace(/^#/, "");
// 当基座下发path时进行跳转
if (data.path && data.path !== router.currentRoute.value.path) {
router.push(data.path as string);
}
}
}
);
}
}
在main.ts中,调用通信方法
import { handleMicroData } from "./utils/MicroTidings"; const app = createApp(App); app.use(router); app.use(createPinia()); app.use(ElementPlus); app.use(http); app.mount("#my-vite-app"); handleMicroData(router);
在页面中给基座传输数据
<template>
<div style="width: 400px;height: 200px;margin: 40px;padding: 20px;background: #c9c9c9;>
子页面内容:
<el-button type="primary" @click="fun_send">子发送</el-button>
</div>
</template>
<script lang="ts" setup>function fun_send(): void { debugger; window.eventCenterForAppNameVite.dispatch({ myname: "child-vite" }); }</script>

其他配置
子项目默认页面跟据参数,加载时默认跳转
子项目收到的参数可存储在 vuex 或者 pinia 中
end.

浙公网安备 33010602011771号