主应用:
安装qiankun:
yarn add qiankun 或 npm i qiankun
注册微应用并启动:
// main.js文件
import { registerMicroApps, loadMicroApp, start, setDefaultMountApp } from 'qiankun';
// 注册微应用并启动
registerMicroApps([
{
name: 'vue2-app',
entry: '//localhost:9001',
container: '#app-subitems',
activeRule: '/app-vue',
},
// 可以注册多个微应用
])
// 如果微应用不是直接跟路由关联的时候,也可以选择手动加载微应用的方式
// loadMicroApp({
// name: 'vue2-code-main',
// entry: '//localhost:9001',
// container: '#app-subitems',
// activeRule: '/subitems',
// })
// 启动 qiankun
start({
prefetch: false, // 取消预加载
});
加载子应用:
// App.vue文件
<template>
<div id="main">
<top-header />
<div class="content-wrapper">
<left-side />
<!-- 子元素的容器id,id是唯一的,不能跟子元素中根元素id相同 -->
<div id="app-subitems"></div>
</div>
</div>
</template>
<script>
import { start } from 'qiankun';
import TopHeader from "./components/TopHeader.vue";
import LeftSide from "./components/LeftSide.vue";
export default {
components: { TopHeader, LeftSide },
data() {
return {
}
},
mounted() {
if (!window.qiankunStarted) {
console.log('start---');
window.qiankunStarted = true;
start({
prefetch: false, // 取消预加载
sandbox: {
experimentalStyleIsolation: false,
}
});
}
},
}
</script>
<style>
* {
padding: 0;
margin: 0;
}
#main {
padding: 0;
margin: 0;
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
.content-wrapper{
display: flex;
justify-content: flex-start;
}
</style>
设置端口号:
// vue.config.js文件
const { name } = require('./package');
module.exports = {
lintOnSave: false,
devServer: {
// 设置服务端口号
port: 9000,
// 自动打开网页
open: true,
},
}
微应用:
新增public-path.js文件:
// public-path.js文件
if(window.__POWERED_BY_QIANKUN__){
__webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
}
main.js修改:
// main.js文件
import "./pubilc-path";
import Vue from 'vue'
import App from './App.vue'
import routes from './router'
import store from './store'
import VueRouter from 'vue-router'
Vue.config.productionTip = false
let router = null,
instance = null;
function render(props = {}) {
const { container } = props;
router = new VueRouter({
base: window.__POWERED_BY_QIANKUN__ ? '/app-vue/' : '/',
mode: 'history',
routes,
})
instance = new Vue({
router,
store,
render: h => h(App)
}).$mount(container ? container.querySelector('#app') : '#app')
};
// 独立运行时
if(!window.__POWERED_BY_QIANKUN__){
render();
}
export async function bootstrap(){
console.log('[vue] vue app bootstrap');
}
export async function mount(props){
console.log('[vue] props from main');
render(props);
}
export async function unmount(){
instance.$destroy();
instance.$el.innerHTML = '';
instance = null;
router = null;
}
vue.config.js修改:
// vue.config.js文件
const { name } = require('./package');
module.exports = {
devServer: {
port: 9001,
open: true,
headers: {
'Access-Control-Allow-Origin': '*',
}
},
configureWebpack: {
output: {
library: `${name}`,
libraryTarget: 'umd', // 把微应用打包成 umd 库格式
},
},
}