如何接入microApp

2024-03-07  本文已影响0人  小遁哥

久闻微前端之名,却没什么机会应用,索性自己学一学。主应用和子应用都是用 vite 搭建的,Micro-App 并不提供脚手架来创建应用,接入子应用的方式也没有细说。

在 main.ts 引入

import microApp from "@micro-zoe/micro-app";
createApp(App).use(piniaInstance).use(router).mount("#micro-app");

注意主应用和子应用挂载的 id 不要是一个名字

一个子应用对应一个路由,为了代码复用,封装一个入口组件 MicroChildApp

<script setup>
import microAppJs from "@micro-zoe/micro-app";
const route = useRoute();
const router = useRouter();
const onBack = () => {
  router.back();
};
const onJumpNotes = () => {
  microAppJs.router.push({ name: "notesChild", path: "/qrCode" });
  data.value = { age: 18 };
};
</script>

<template>
  <div>
    <el-button @click="onBack">返回</el-button>
    <el-button @click="onJumpNotes">二维码</el-button><br /><br />
  </div>
  <micro-app
    keep-alive
    :name="route.name"
    iframe
    :url="route.meta.url"
    :defaultPage="route.meta.defaultPage"
  ></micro-app>
</template>

<style lang="less" scoped></style>

HomePage.vue 用于路由切换

<script setup>
import { useRouter } from "vue-router";
const router = useRouter();

const onJumpVue3 = () => {
  router.push({ name: "vue3Child" });
};
const onJumpNotes = () => {
  router.push({ name: "notesChild" });
};
</script>

<template>
  <div :class="['home-page-wrap']">
    <el-button @click="onJumpNotes">sf-notes</el-button><br /><br />
    <el-button @click="onJumpVue3">sf-vue3</el-button>
  </div>
</template>

<style lang="less" scoped>
.home-page-wrap {
}
</style>


路由配置

import {
  createRouter,
  RouteRecordRaw,
  Router,
  createWebHistory,
} from "vue-router";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "Home",
    component: () => import("@/views/HomePage.vue"),
    meta: {
      title: "首页",
    },
  },
  {
    path: "/notesChild",
    name: "notesChild",
    component: () => import("@/components/MicroChildApp.vue"),
    meta: {
      title: "sf-notes",
      url: "http://localhost:8000/notes",
      defaultPage: "/qrCode",
    },
  },
  {
    path: "/vue3Child",
    name: "vue3Child",
    component: () => import("@/components/MicroChildApp.vue"),
    meta: {
      title: "sf-vue3",
      url: "http://localhost:5173",
    },
  },
];

const router: Router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;

vite 框架要加 iframe 属性,否则会出现 VM572:28 [micro-app from runScript] app vue3Child: SyntaxError: Cannot use import statement outside a module 的报错

import microApp from '@micro-zoe/micro-app'
microApp.router.push({name: 'my-app', path: '/page1'})

这种指定了子应用 path 的,必须要等到子应用加载完成且处于活跃状态才能生效,keep-alive 并不能保证这种跳转,否则会报错[micro-app] navigation failed, app does not exist or is inactive,而使用router.push({ name: "vue3Child", path: "/qrCode" });方式跳转的还是默认页面

上一篇下一篇

猜你喜欢

热点阅读