全局状态管理Store
- 通过发布订阅者模式封装一个全局Store
main/micro/store/index.js
export const createStore = (initData = {}) => (() => {let store = initDataconst observers = [] // 管理所有的订阅者,依赖// 获取storeconst getStore = () => store// 更新storeconst update = (value) => {if (value !== store) {// 执行store的操作const oldValue = store// 将store更新store = value// 通知所有的订阅者,监听store的变化observers.forEach(async item => await item(store, oldValue))}}// 添加订阅者const subscribe = (fn) => {observers.push(fn)}return {getStore,update,subscribe}})()
-
主应用使用全局状态管理
在主应用中创建全局Store实例,并订阅数据更新
- main/src/utils/startMicroApp.js ```javascript import { registerMicroApps, start, createStore } from ‘../../micro’;
const store = createStore(); window.store = store;
store.subscribe((newValue, oldValue) => { console.log(newValue, oldValue); })
<a name="rz79H"></a># 子应用获取数据并更新数据- vue3/src/main.js```javascriptconst storeData = window.store.getStore()window.store.update({...storeData,a: 778,})
