美文网首页
qiankun框架Vue3子应用(webpack)

qiankun框架Vue3子应用(webpack)

作者: 风凌摆渡人 | 来源:发表于2023-05-07 10:07 被阅读0次

核心逻辑

  1. 判断是否在乾坤框架中
  2. 否安装正常方式挂载
  3. 是不进行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('')

// 全局调用乾坤框架消息方便进行消息传递
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)!
}

/**
 * 应用每次进入都会调用 mount 方法,通常我们在这里触发应用的渲染方法
 */
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'))
}

/**
 * 应用每次 切出/卸载 会调用的方法,通常在这里我们会卸载微应用的应用实例
 */
const unmount = async () => {
  app.unmount()
  if (history) {
    history.destroy()
  }
}

// bootstrap 只会在微应用初始化的时候调用一次,下次微应用重新进入时会直接调用 mount 钩子,不会再重复触发 bootstrap。
// 通常我们可以在这里做一些全局变量的初始化,比如不会在 unmount 阶段被销毁的应用级别的缓存等。
const bootstrap = async () => {
  console.log('%c%s', 'color: green;', 'vue3.0 app bootstrap')
}

/**
 * 可选生命周期钩子,仅使用 loadMicroApp 方式加载微应用时生效
 */
const update = async (props: any) => {
  console.log('update props', props)
}

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

主应用:https://www.jianshu.com/p/48d74801b4c4
子应用链接:https://www.jianshu.com/p/6c3feb4c1062
vite子应用:https://www.jianshu.com/p/d364e6621b63

相关文章

网友评论

      本文标题:qiankun框架Vue3子应用(webpack)

      本文链接:https://www.haomeiwen.com/subject/tuphsdtx.html