一、微前端之实践主应用的生命周期、微前端的生命周期、 加载和解析 html 及 js
- 主应用的生命周期,如下所示:
- 在主应用
main
下的 util
中的 index.js
中,在 registerApp
中的 registerMicroApps
方法注册到微前端框架里,传入第二个参数生命周期,beforeLoad
是开始加载,mounted
是渲染完成,destoryed
是卸载完成,index.js
,代码如下:
import {
registerMicroApps, start, createStore } from '../../micro'
import {
loading } from '../store'
const store = createStore();
window.store = store;
store.subscribe((newValue, oldValue) => {
console.log(newValue, oldValue, '---')
})
export const registerApp = (list) => {
registerMicroApps(list, {
beforeLoad: [
() => {
loading.changeLoading(true)
console.log('开始加载')
}
],
mounted: [
() => {
loading.changeLoading(false)
console.log('渲染完成')
}
],
destoryed: [
() => {
console.log('卸载完成')
}
]
})
start();
}
- 在
micro
下的 start.js
中,registerMicroApps
接收两个参数,appList
子应用参数列表和 lifeCycle
生命周期,然后通过 setMainLifecycle
设置主应用的生命周期,代码如下:
export const registerMicroApps = (appList, lifeCycle) => {
setList(appList);
setMainLifecycle(lifeCycle);
}
- 在
micro
下的 const
中 mainLifeCycle.js
,lifecycle
是主应用的生命周期,getMainLifecycle
是获取主应用的生命周期,setMainLifecycle
是缓存主应用的生命周期,代码如下:
let lifecycle = {
};
export const getMainLifecycle = () => lifecycle;
export const setMainLifecycle = data => lifecycle = data;
- 微前端的生命周期,如下所示:
- 在
micro
下的 util
中 index.js
,findAppByRoute
查找上一个和下一个 app
里面的内容,isTurnChild
判断子应用是否做了切换,通过 window.__CURRENT_SUB_APP__
判断当前路由以改变,修改当前路由,通过 window.__CURRENT_HASH__
判断当前 hash
值是否改变,代码如下所示:
import {
getList } from "../const/subApps";
export const patchRouter = (globalEvent, eventName) => {
return function () {