qiankun框架Vue3子應(yīng)用(webpack)

核心邏輯

  1. 判斷是否在乾坤框架中
  2. 否安裝正常方式掛載
  3. 是不進(jìn)行app掛載,而是通過乾坤暴露的mount方法掛載

main.ts文件

import { createApp } from 'vue'
import App from './App.vue'
import routes from './router'
import { createRouter, createWebHashHistory } from 'vue-router'
import './public-path.js'
export { mount, unmount, bootstrap } from './qiankun'

if (!(window as any).__POWERED_BY_QIANKUN__) {
  const router = createRouter({
    history: createWebHashHistory(),
    routes
  })
  createApp(App).use(router).mount('#app')
}

qiankun.ts

import { RouterHistory, createRouter, createWebHashHistory } from 'vue-router'
import { App, inject, InjectionKey, createApp } from 'vue'
import routes from './router'
import MainApp from './App.vue'
let history: RouterHistory | null = null
let app: any = null

interface IGlobalState {
  setGlobalState: (state: Record<string, any>)=> void
  onGlobalStateChange: (func: (state: Record<string, any>, prev: Record<string, any>)=> void)=> void
  offGlobalStateChange: () => boolean
}

export const GlobalStateKey: InjectionKey<IGlobalState> = Symbol('')

// 全局調(diào)用乾坤框架消息方便進(jìn)行消息傳遞
const createGlobalState = (props: any) => {
  const globalState = {
    install (app: App) {
      app.config.globalProperties.$globalState = props
      app.provide(GlobalStateKey, props)
    }
  }
  return globalState
}

// vue3 use
const useGlobalState = () => {
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  return inject(GlobalStateKey)!
}

/**
 * 應(yīng)用每次進(jìn)入都會(huì)調(diào)用 mount 方法,通常我們在這里觸發(fā)應(yīng)用的渲染方法
 */
const mount = async (props: any) => {
  const { container } = props
  history = createWebHashHistory('/meeting/')
  const router = createRouter({
    history,
    routes
  })
  app = createApp(MainApp)
  app.use(router).use(createGlobalState(props)).mount(container.querySelector('#app'))
}

/**
 * 應(yīng)用每次 切出/卸載 會(huì)調(diào)用的方法,通常在這里我們會(huì)卸載微應(yīng)用的應(yīng)用實(shí)例
 */
const unmount = async () => {
  app.unmount()
  if (history) {
    history.destroy()
  }
}

// bootstrap 只會(huì)在微應(yīng)用初始化的時(shí)候調(diào)用一次,下次微應(yīng)用重新進(jìn)入時(shí)會(huì)直接調(diào)用 mount 鉤子,不會(huì)再重復(fù)觸發(fā) bootstrap。
// 通常我們可以在這里做一些全局變量的初始化,比如不會(huì)在 unmount 階段被銷毀的應(yīng)用級別的緩存等。
const bootstrap = async () => {
  console.log('%c%s', 'color: green;', 'vue3.0 app bootstrap')
}

/**
 * 可選生命周期鉤子,僅使用 loadMicroApp 方式加載微應(yīng)用時(shí)生效
 */
const update = async (props: any) => {
  console.log('update props', props)
}

export { mount, unmount, bootstrap, update, useGlobalState }

主應(yīng)用:http://www.itdecent.cn/p/48d74801b4c4
子應(yīng)用鏈接:http://www.itdecent.cn/p/6c3feb4c1062
vite子應(yīng)用:http://www.itdecent.cn/p/d364e6621b63

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容