首先我的主应用和子应用都是vue开发的,并且路由模式是hash模式的
主应用
1.安装qiankun
yarn add qiankun # 或者 npm i qiankun -S
2.在主应用中注册微应用
main.js中
import {registerMicroApps, start,addErrorHandler} from 'qiankun';
const getActiveRule = (hash) => (location) => location.hash.startsWith(hash);
const apps = [
{
name: 'qiankun-vue-common', // 应用的名字
entry: '/child/vue-hash/', // 默认加载这个html,解析里面的js动态的执行(子应用必须支持跨域,内部使用的是 fetch)
container: '#common', // 要渲染到的容器名id
activeRule: getActiveRule('#/common') // 通过哪一个路由来激活
}
];
registerMicroApps(apps); // 注册应用
start(); // 开启应用
addErrorHandler((event)=>{//当子页面未开启的时候
console.log(event);
if(event){
router.push({path:'/404'})
}
})
在 app.vue 中
<template>
<div id="apps">
<router-view v-if="isRouterAlive" />
<div id="vue"></div>
<div id="common"></div>
</div>
</template>
3.子应用
1.在入口文件main.js修改
let instance = null;
function render(props) {
instance = new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
}
Vue.prototype.bus = new Vue()
if (!window.__POWERED_BY_QIANKUN__) { // 如果是独立运行,则手动调用渲染
render();
}
if(window.__POWERED_BY_QIANKUN__){ // 如果是qiankun使用到了,则会动态注入路径
__webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
}
// 根据 qiankun 的协议需要导出 bootstrap/mount/unmount
export async function bootstrap(props) {
};
export async function mount(props) {
render(props);
};
export async function unmount(props) {
instance.$destroy();
};
2.在配置文件修改
module.exports = {
devServer: {
headers: {
'Access-Control-Allow-Origin': '*',
},
},
configureWebpack: {
output: {
library: 'qiankun-vue-common',
libraryTarget: 'umd'
},
},
};
3.由于我使用的路由模式是hash模式的
修改路由方式
微应用的配置有两种方案:
一种是所有的路由都是采用平铺式(即所有路由都在同一层级),但这种配置方式需要在每个路由前都要加上前缀 “/vueChild”,包括所有的route-link标签的to属性也都需要添加此前缀
另一种方案就是额外新建一个空白的路由页面,将其它所有的路由都作为它的子路由(放在children属性中),这种方式放在children中的子路由不需要在每个路由中都加前缀 /vueChild,但是也不能加 “/”,否则就跳转到了跟目录下,也容易与主应用路由冲突
两种方式都可以实现hash模式的微前端应用
我使用的是第一种
const routes = [
{
path:'/common/home',
name: 'Home',
component:()=>import('../views/Home.vue')
},
{
path:'/common/about',
name: 'About',
component:()=>import('../views/About.vue')
}
]