1

我正在通过遵循微前端架构来创建一个大型应用程序。比方说,我已经将我的整个应用程序分为 5 个微应用程序(micro-app-A(在 Vue 中)、micro-app-B(在 Vue 中)、micro-app-C(在 Angular 中)、micro-app-D(在 React 中)和一个 shell 应用程序 My-App-Shell(在 Vue 中))

我使用pubsub-js(一个用 JavaScript 编写的基于主题的发布/订阅库)在微应用中的不同组件之间进行通信。我的每个微应用都完美地使用了这个 pubsub 系统在它自己的组件之间进行通信。但我需要一个通用的 pubsub 系统(由我的 shell 应用程序管理)来在不同的微应用程序之间进行通信。

如何做到这一点?

4

1 回答 1

2

CustomEvent您可以轻松地在此处构建抽象:

const handlers = {};

window.publish = (topic, message) => {
  var ev = new CustomEvent('pubsub', {
    detail: { topic, message },
  });
  document.body.dispatchEvent(ev);
};

window.subscribe = (topic, handler) => {
  const topicHandlers = handlers[topic] || [];
  topicHandlers.push(handler);
  handlers[topic] = topicHandlers;
};

window.unsubscribe = (topic, handler) => {
  const topicHandlers = handlers[topic] || [];
  const index = topicHandlers.indexOf(handler);
  index >= 0 && topicHandlers.splice(index, 1);
};

document.body.addEventListener('pubsub', ev => {
  const { topic, message } = ev.detail;
  const topicHandlers = handlers[topic] || [];
  topicHandlers.forEach(handler => handler(message));
});

(有关演示,请参阅:https ://jsfiddle.net/qo5nca71/ )

在大多数情况下,这应该足够了。如果你想获得更多的“安全性”(例如,微前端不能改变抽象,这些抽象在上面的 impl. 中只是全局可用的)我建议使用更复杂的方法,比如 Piral 中的事件机制(参见https:// github.com/smapiot/piral)。

于 2020-02-02T13:23:39.007 回答