qiankun示例
大约 3 分钟
qiankun 示例
项目地址
搭建基座项目
在命令行中运行以下命令
pnpm create vue@latest跟着步骤搭建项目
基座应用改造
删除无用文件,仅保留 App.vue,删除 router/index.ts 中无用路由,删除 src/main.css 中无用样式
// router/index.ts
import { createRouter, createWebHistory } from 'vue-router';
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [],
});
export default router;/* src/main.css */
@import './base.css';
#app {
  width: 100%;
  height: 100vh;
}安装个性化插件
安装 ui 框架和 sass 处理器
pnpm install ant-design-vue@4.x @ant-design/icons-vue --save
pnpm install sass sass-loader --save-dev改造 App.vue
<template>
  <a-layout :style="layoutStyle">
    <a-layout-sider :style="siderStyle">
      <a-menu
        v-model:openKeys="openKeys"
        v-model:selectedKeys="selectedKeys"
        mode="inline"
        :items="items"
        @click="handleClick"
      ></a-menu
    ></a-layout-sider>
    <a-layout>
      <a-layout-header :style="headerStyle">子项目</a-layout-header>
      <!-- #microApp 为子项目挂载/渲染容器 -->
      <a-layout-content :style="contentStyle" id="microApp"></a-layout-content>
    </a-layout>
  </a-layout>
</template>
<script lang="ts" setup>
import { ref, type CSSProperties, VueElement, reactive } from 'vue';
import type { ItemType, MenuProps } from 'ant-design-vue';
import router from './router';
const layoutStyle: CSSProperties = {
  height: '100%',
};
const headerStyle: CSSProperties = {
  textAlign: 'center',
  lineHeight: '60px',
  color: '#fff',
};
const contentStyle: CSSProperties = {};
const siderStyle: CSSProperties = {};
const selectedKeys = ref<string[]>(['Vue2']);
const openKeys = ref<string[]>(['1']);
function getItem(
  label: VueElement | string,
  key: string,
  icon?: any,
  children?: ItemType[],
  type?: 'group'
): ItemType {
  return {
    key,
    icon,
    children,
    label,
    type,
  } as ItemType;
}
const items: ItemType[] = reactive([
  getItem('子项目', '1', null, [
    getItem(
      'Vue',
      'vue',
      null,
      [
        getItem('Vue2-1', 'app1'),
        getItem('Vue2-2', 'app2'),
        getItem('Vue3+vite+ts', 'app3'),
      ],
      'group'
    ),
    getItem('React', 'react', null, [getItem('React18', 'app4')], 'group'),
  ]),
]);
const handleClick: MenuProps['onClick'] = (e) => {
  console.log('click', e);
  router.push({
    path: `/${e.key}`,
  });
};
</script>
<style lang="scss" scoped></style>使用 qiankun
安装 qiankun
pnpm install qiankun改造 main.ts
import './assets/main.css';
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import Antd from 'ant-design-vue';
import { registerMicroApps, start } from 'qiankun';
import type { RegistrableApp } from 'qiankun';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(createPinia());
app.use(router);
app.use(Antd);
app.mount('#app');
const apps: RegistrableApp<any>[] = [
  {
    name: '',
    entry: '',
    container: '',
    activeRule: '',
  },
];
registerMicroApps(apps);
start();