微前端之获取首个子应用与设置主应用生命周期

28 阅读1分钟

本文主要内容包括:如何获取首个子应用与如何设置主应用生命周期?

获取首个子应用

获取首个子应用的时机在注册完子应用列表之后,也就是 registerApp 里的 start 方法。

const filterApp = (key, value) => {
  const currentApp = getList().filter(item => item[key] === value)
  return currentApp.length ? currentApp[0] : {}
}

export const currentApp = () => {
  const currentUrl = window.location.pathname
  return filterApp('activeRule', currentUrl)
}

// 启动微前端框架
export const start = () => {
  // 首先验证当前子应用列表是否为空
  const apps = getList()

  if (!apps.length) {
    // 子应用列表为空
    throw Error('子应用列表为空,请正确注册'); // 也可以用 return 替代
  }
  // 有子应用的内容,查找到符合当前路由的子应用
  const app = currentApp()
  console.log(app, '有子应用的内容,查找到符合当前路由的子应用');
  if (app) {
    const { pathname, hash } = window.location
    const url = pathname + hash
    window.history.pushState('', '', url)
    window.__CURRENT_SUB_APP__ = app.activeRule
  }
}

export const registerApp = (list) => {
  // 注册到微前端框架里
  registerMicroApps(list)
  // 开启微前端框架
  start()
}

主应用生命周期

设置主应用生命周期,需要为方法 registerMicroApps 增加生命周期参数。

/** loading.js start */
export let loadingStatus = ref(true) // 主应用使用 Vue3 开发,子应用加载前 loadingStatus 为 true

export const changeLoading = type => loadingStatus.value = type

/** loading.js end */

let lifeCycle = {}

export const getMainLifeCycle = () => lifeCycle

export const setMainLifeCycle = data => lifeCycle = data

export const registerMicroApps = (appList, lifeCycle) => {
  setList(appList)
  setMainLifeCycle(lifeCycle)
}

registerMicroApps(list, {
  beforeLoad: [
    // 方法不限一个
    // 可以加一些权限验证
    () => {
      loading.changeLoading(true)
      console.log('开始加载');·
      
    }
  ],
  mounted: [
    // 方法不限一个
    () => {
      loading.changeLoading(false)
      console.log('渲染完成');
      
    }
  ],
  destroyed: [
    // 方法不限一个
    () => {
      console.log('卸载完成');
      
    }
  ]
})