继上一次vue3+vite+qiankun搭建微前端,这次处理下主应用和微应用的路由问题
主应用和微应用都是使用 History 路由模式
主要问题集中在各个模块的路由返回
- 微应用返回微应用
- 主应用返回微应用
相当于:/platform/test -> /main/home -> /test
微路由/platform/test跳转到主路由/main/home(或微路由),再返回微路由变成/test
这里都是用到了主应用的路由机制,返回时匹配不到微应用路由,页面就报404了
这边的解决方案是:完整路由替换微应用路由,浏览器才能识别到
- 主应用的跳转会记录history的历史记录里面,返回是正常的;
- 微应用是根据路由规则动态加载了一个容器组件,跳转到微应用的路由是没有记录到history的;
监听浏览器前进后退事件,将微应用路由替换成完整路由
dart
```
// 监听浏览器前进后退事件
window.addEventListener('popstate', (event) => {
if (window.history.state) {
//current表示前进或后退的路由,意思是点击跳转或者返回上一页都是当前地址栏的路由
console.log(window.history.state)
const index=navList.value.findIndex(item=>item.path.includes(window.history.state.current));
if(index>-1){
//只处理qiankun的路由
if(navList.value[index].isQianKun){
console.log(navList.value[index].path,'qiankun监听');
//将完整路由替换当前的微应用路由
window.history.replaceState(null, null, navList.value[index].path);
}
}
}
});
```
php
const navList=ref([
{
path:'/platform/child-test',
isQianKun:true,
name:'微应用1',
},
{
path:'/platform/platform-child/child-test2',
isQianKun:true,
name:'微应用2',
},
{
path:'/hrm/hrmLeave',
isQianKun:false,
name:'请假申请',
},
{
path:'/hrm/hrmLeaveStatistics',
isQianKun:false,
name:'请假统计',
}
])
const nav=(url,item)=>{
if(proxy.$route.path ===url) return;
proxy.$router.push({path:url});
}
ini
<template v-for="item in navList">
<el-button @click="nav(item.path,item)">{{item.name}}</el-button>
</template>