首先在主应用里安装qiankun
npm i qiankun -S
主应用 main.js 里注册微应用
import { registerMicroApps } from 'qiankun';
// 注册子应用;
registerMicroApps([
{
name: 'LsMaintenance',
entry:process.env.NODE_ENV === 'production' ? '/****/' : '子应用的地址',
container: '#order-container',
activeRule: '/LsMaintenance',
props: {
store,
router: router,
},
},
]);
props 传给子应用的值
app.vue(在合适的地方) 放入子容器 并启动
<div id="order-container"></div>
onMounted(() => {
if (!window.qiankunStarted) {
window.qiankunStarted = true;
start();
}
});
子应用不需要下载qiankun.js;
因现在qiankun暂不支持vite所以我们可以用社区开发的 vite-plugin-qiankun
npm i vite-plugin-qiankun -S
配置子应用 main.js
import { qiankunWindow, renderWithQiankun } from 'vite-plugin-qiankun/dist/helper';
let instance = null;
function render(props = {}) {
const { container } = props;
const ShareStore = props.store //主应用传过来的store;
const ShareRouter = props.router //主应用传过来的router;
// Vue.prototype.$ShareStore = ShareStore.state.value;
Vue.prototype.$ShareRouter = ShareRouter;
if (ShareStore) {
Vue.prototype.$ShareStore = ShareStore.state.value;
} else {
Vue.prototype.$ShareStore = {
app: {},
};
}
instance = new Vue({
pinia: ShareStore,
router,
render: (h) => h(App),
}).$mount(container ? container.querySelector('#app') : '#app');
}
renderWithQiankun({
// 加载微应用
mount(props) {
console.log('--mount,复用项目');
render(props);
},
// 启动微应用
bootstrap() {
console.log('--bootstrap');
},
// 卸载微应用
unmount() {
// console.log('--unmount');
instance.$destroy();
instance = null;
},
});
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
render({});
}
配置子应用 router.js
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';
const createRouter = () =>
new VueRouter({
mode: 'history', // if use history mode, require service support
base: qiankunWindow.__POWERED_BY_QIANKUN__ ? '/LsMaintenance' : '',
routes: [
{
path: '/',
name: 'home',
component: () => import('../views/HomeView.vue'),
},
],
});
const router = createRouter();
export default router;
配置子应用 vite.config.js
import qiankun from "vite-plugin-qiankun";
export default defineConfig({
plugins: [
vue(),
qiankun('LsMaintenance', {
useDevMode: true
})
],
server: {
port: 9000,
headers: {
'Access-Control-Allow-Origin': '*'
}
},
})