笔记:无界微前端入门

无界微前端框架笔记

wujie(无界)是腾讯在 2022 年 7 月推出的微前端框架,下面是腾讯前端团队的原话

无界微前端方案基于 webcomponent 容器 + iframe 沙箱,能够完善的解决适配成本、样式隔离、运行性能、页面白屏、子应用通信、子应用保活、多应用激活、vite 框架支持、应用共享等用户的核心诉求。

简单实现

以 vite 创建的两个 vue3 项目为例(分别为主应用 main 和子应用 son1)

  1. 主应用安装 wujie-vue3 依赖
yarn add wujie-vue3
  1. 主应用引入 wujie-vue3
/* main项目->main.js */
import {
    
     createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router/index'
import WujieVue from 'wujie-vue3'

createApp(App).use(router).use(WujieVue).mount('#app')
  1. 主应用配置路由
/* main项目->router/index.js */
import {
    
     createRouter, createWebHistory } from 'vue-router'

export const routes = [
  {
    
    
    path: '/'
  },
  {
    
    
    path: '/son-1',
    component: () => import('../views/son1.vue')
  }
]

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

export default router
<!-- main项目->view/son1.vue  -->
<template>
  <!--单例模式,name相同则复用一个无界实例,改变url则子应用重新渲染实例到对应路由 -->
  <WujieVue width="100%" height="100%" name="son-1" :url="url" :sync="true"></WujieVue>
</template>

<script>
  export default {
    data() {
      return {
        url: 'http://localhost:4002/' //这个是子应用开启的服务地址,可在vite.config.js中自行配置
      }
    }
  }
</script>
  1. 主应用配置路由跳转
<!-- main项目->App.vue  -->
<script setup></script>

<template>
  <router-link to="/son-1">son1</router-link>
  <router-link to="/son-2">son2</router-link>
  <router-view></router-view>
</template>
  1. 子应用接入主应用
/* son1项目->main.js  */
import {
    
     createApp } from 'vue'
import './style.css'
import App from './App.vue'

if (window.__POWERED_BY_WUJIE__) {
    
    
  let instance
  window.__WUJIE_MOUNT = () => {
    
    
    const router = createRouter({
    
     history: createWebHistory(), routes })
    instance = createApp(App)
    instance.use(router)
    instance.mount('#app')
  }
  window.__WUJIE_UNMOUNT = () => {
    
    
    instance.unmount()
  }
} else {
    
    
  createApp(App)
    .use(createRouter({
    
     history: createWebHistory(), routes }))
    .mount('#app')
}
  1. 启动子应用和主应用
    注意:子应用启用之后的端口域名要对应主应用中的域名

wujie 是如何通过路由去控制子应用的?

路由同步会将子应用路径的 path+query+hash 通过 window.encodeURIComponent 编码后挂载在主应用 url 的查询参数上,其中 key 值为子应用的 name。

开启路由同步后,刷新浏览器或者将 url 分享出去子应用的路由状态都不会丢失,当一个页面存在多个子应用时无界支持所有子应用路由同步,浏览器刷新、前进、后退子应用路由状态也都不会丢失

猜你喜欢

转载自blog.csdn.net/Big_YiFeng/article/details/130221808