Skip to content

Latest commit

 

History

History

qiankun-demo

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 

README.md

qiankun demo

线上地址:https://maxlz1.github.io/micro-app-demos/qiankun-demo/vue3-main/

本地启动命令

pnpm i
pnpm run qiankun-demo:start

启动后自动打开主应用,如果未打开页面,使用浏览器输入http://localhost:8081进行访问

各应用本地地址:

文件目录

└── qiankun-demo
    ├── react-child # react18子应用(作为嵌套应用的主应用)
    ├── vite-child # react18-vite子应用
    ├── vue2-child # vue2子应用
    └── vue3-main # vue3主应用

功能列表

  • 应用间通信(利用CustomEvent)
  • 多个子应用共存
  • CSS隔离
  • 主子应用间跳转
  • 嵌套子应用
  • 资源预加载
  • 子应用保活
  • 接入vite子应用

功能实现说明

应用间通信

考虑到qiankun3后续抛弃globalState,所以应用间通信未使用qiankun自带的globalState。

主要思路就是利用CustomEvent。

主应用使用window.dispatchEvent(new CustomEvent(...))向子应用下发数据,子应用使用window.addEventListener监听数据变化。

主应用:

import type { User } from '@/data/userData'

export const CHANGE_USER = 'changeUser'

function createUserEvent(user: User | null) {
  return new CustomEvent(CHANGE_USER, {
    detail: user
  })
}

export function dispatchUserEvent(user: User | null) {
  const event = createUserEvent(user)
  window.dispatchEvent(event)
}

子应用:

function changeUserListener(e: Event) {
  const { setUser } = useUserStore()
  setUser((e as CustomEvent<User>).detail)
}

window.addEventListener('changeUser', changeUserListener)

多个子应用共存

注意子应用共存时,Vue子应用需要使用abstract路由,React使用MemoryRouter

利用loadMicroApp实现子应用共存。加载子应用时通过props传入要跳转的路径,子应用接收path,根据path使用abstract或MemeryRouter进行跳转。

Vue2

export const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes,
})

export const abstractRouter = new VueRouter({
  mode: 'abstract',
  base: process.env.BASE_URL,
  routes,
})

function render(props?: Prop) {
  let container: null | HTMLElement = null
  if (props && props.container) {
    container = props.container
  }
  const vueContainer = container ? (container.querySelector('#app') as Element) : '#app'

  if (props?.path) {
    routerInstance = abstractRouter
  } else {
    routerInstance = router
  }

  instance = new Vue({
    router: routerInstance,
    pinia: createPinia(),
    render: (h) => h(App),
  }).$mount(vueContainer)

  if (props?.path) {
    routerInstance.push(props.path)
  }
}

React

export const router = createHashRouter(routes, {
  basename
})

export const memoryRouter = createMemoryRouter(routes, {
  basename
})

function render(props?: Prop) {
  let container: null | HTMLElement = null
  if (props && props.container) {
    container = props.container
  }

  let appContainer = (container ? container.querySelector('#root') : document.getElementById('root')) as HTMLElement

  root = ReactDOM.createRoot(appContainer)

  root.render(
    <React.StrictMode>
      <Provider store={store}>
        <ConfigProvider prefixCls="ar4" getPopupContainer={node => {
          if (node) {
            return node.parentNode as HTMLElement
          }
          return appContainer
        }}>
          <Suspense fallback={
            <Spin>
              <div style={{width: '100%', height: '200px'}}></div>
            </Spin>
          }>
            <RouterProvider router={props?.path ? memoryRouter : router} />
          </Suspense>
        </ConfigProvider>
      </Provider>
    </React.StrictMode>
  )

  if (props?.path) {
    memoryRouter.navigate(props.path)
  }
}

CSS隔离

框架处理:ant design提供了统一修改CSS前缀的方案(子应用统一将Select, Tooltip等组件挂载到父节点上)

正常情况使用scoped、module css等方式进行隔离。

主子应用间跳转

  • 主应用跳转到子应用:主应用直接使用本身的路由对象进行跳转即可。

    <router-link to="/main/communication-test">
      <a-button type="primary">跳转至主应用 page1</a-button>
    </router-link>
    <router-link to="/vue2App/communication-test">
      <a-button type="primary">跳转至Vue2子应用</a-button>
    </router-link>
    <router-link to="/reactApp/communication-test">
      <a-button type="primary">跳转至React18子应用</a-button>
    </router-link>
    <router-link to="/viteApp/communication-test">
      <a-button type="primary">跳转至Vite子应用</a-button>
    </router-link>
  • 子应用跳转到主应用:Vue子应用直接使用自身路由对象进行跳转;React使用react-router进行跳转后会添加basename,所以跳转采用window.pushState。

    <router-link to="/main/communication-test">
      <a-button type="primary">跳转至主应用 page1</a-button>
    </router-link>
    <router-link to="/vue2App/communication-test">
      <a-button type="primary">跳转至Vue2子应用</a-button>
    </router-link>
    <router-link to="/reactApp/communication-test">
      <a-button type="primary">跳转至React18子应用</a-button>
    </router-link>
    <router-link to="/viteApp/communication-test">
      <a-button type="primary">跳转至Vite子应用</a-button>
    </router-link>
    export default function NavigateView() {
      const handleClick = ({ url }: { url: string }) => {
        window.history.pushState({}, '', window.location.pathname + url)
      }
      const buttons = [
        {
          url: '#/main/communication-test',
          label: '跳转至主应用 page1'
        },
        {
          url: '#/vue2App/communication-test',
          label: '跳转至Vue2子应用'
        },
        {
          url: '#/reactApp/communication-test',
          label: '跳转至React18子应用'
        },
        {
          url: '#/viteApp/communication-test',
          label: '跳转至Vite子应用'
        },
      ].map(item => (
        <Button type="primary" onClick={() => handleClick(item)} key={item.url}>{item.label}</Button>
      ))
    
      return (
        <>
          <Typography.Title>React18子应用内控制跳转</Typography.Title>
          <Space size={20}>
            {buttons}
          </Space>
        </>
      )
    }
  • 子应用跳转到子应用:同子应用跳转到主应用。

资源预加载

使用qiankun提供的prefetchApps方法进行资源的预加载。

子应用保活

利用主应用的keep-alive进行子应用的保活。主应用创建加载子应用的view,并将这个view加入keep-alive列表中。

主应用router-view所在view

<template>
  <router-view v-slot="{ Component }">
    <keep-alive :include="aliveView">
      <component :is="Component" />
    </keep-alive>
  </router-view>
</template>

<script lang="ts" setup>
const aliveView = reactive<string[]>([
  'Vue2KeepAliveView',
  'React18KeepAliveView',
  'ViteKeepAliveView'
])
</script>

Vue2KeepAliveView.vue

<template>
  <div ref="container"></div>
</template>

<script lang="ts">
export default {
  name: 'Vue2KeepAliveView'
}
</script>

<script lang="ts" setup>
import { loadMicroApp, type MicroApp } from 'qiankun'
import { onBeforeUnmount, onMounted, ref } from 'vue'
import { vue2AppEntry } from '@/data/appData'

const container = ref<HTMLElement | null>(null)

let app: MicroApp | null = null

onMounted(() => {
  app = loadMicroApp({
    name: 'vue2AppKeepAlive',
    entry: vue2AppEntry,
    container: container.value!,
    props: {
      path: '/vue2App/tab-view'
    }
  })
})

onBeforeUnmount(async () => {
  if (app && app.getStatus() === 'MOUNTED') {
    await app.unmount()
  }
  app = null
})
</script>

<style lang="less" scoped></style>

接入vite子应用

vite子应用的接入依靠vite-plugin-qiankun插件。