修复微前端无界[wujie]子应用window属性值在初始化后不再变化的问题

问题

部分的组件库(例如antd)使用到了window.innerWidthwindow.innerHeight属性,可无界框架在初始化时仅将主应用的innerWidthinnerHeight属性赋值给子应用,后续不管主应用如何变化,子应用的这两个属性无法跟随变化,也就导致子应用使用的这些组件库表现异常。
image

解决方式1

借用作者在交流群中的说明,使用Object.defineProperty重写对应属性的getter即可image

  • 故在此借助无界的插件系统,可以按照下面的方式(重写getter)进行属性指向修正。
  • 不只是innerWidth和innerHeight,其他属性也可以这样处理。
<script setup>
import WujieVue from "wujie-vue3";
const plugins = [
  {
    // 在子应用所有的js之前
    jsBeforeLoaders: [
      {
        callback(appWindow: typeof window) {
          type PropListItem = keyof typeof window;
          // 后续若有其他属性需要修正,只需在这里添加需要重写的属性即可
          const propsNeedAdjust:PropListItem[] = ["innerWidth", "innerHeight"];
          const adjustPropsProxy = (prop: PropListItem) => {
            Object.defineProperty(appWindow, prop, {
              get: function () {
                if (appWindow.__POWERED_BY_WUJIE__) {
                  return appWindow.parent[prop];
                } else {
                  // 返回原始值
                  return appWindow[prop];
                }
              }
            });
          };
          propsNeedAdjust.forEach(prop => {
            adjustPropsProxy(prop);
          });
        }
      }
    ]
  }
];
</script>

<template>
  <WujieVue :plugins="plugins" />
</template>

解决方式2

使用wujie-polyfill@1.0.11或更高版本,引入WindowSizePlugin即可

import { startApp } from 'wujie'
import { WindowSizePlugin } from "wujie-polyfill";

// 无框架
setupApp({
    name: '唯一id',
    url: '子应用地址',
    exec: true,
    el: '容器',
    sync: true
    plugins: [WindowSizePlugin()]
})

// vue
<WujieVue
  width="100%"
  height="100%"
  name="xxx"
  :url="xxx"
  :plugins=“[WindowSizePlugin()]”
></WujieVue>

// react
<WujieReact
  width="100%"
  height="100%"
  name="xxx"
  url="{xxx}"
  plugins="{[WindowSizePlugin()]}"
></WujieReact>
posted @ 2023-12-19 11:12  脆皮鸡  阅读(435)  评论(0编辑  收藏  举报