vue3+qiankun主应用和微应用的路由跳转返回

继上一次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>
相关推荐
Doris_202313 小时前
说一说ESLint+Prettier生效的原理
前端·设计模式·架构
ZC跨境爬虫13 小时前
跟着 MDN 学CSS day_21:(图像溢出控制与表单元素样式定制)
前端·javascript·css·ui·交互
卷帘依旧14 小时前
微前端解决方案-qiankun
前端
moshuying14 小时前
你做的,比汇报出来的多得多
前端
shuye21614 小时前
google chrome 离线下载地址
前端·chrome
yqcoder14 小时前
闭包是什么?优缺点、怎么防内存泄漏?
前端·http
lichenyang45314 小时前
鸿蒙 ArkUI 组件基础复盘:从两个 UI 卡片回到 ComponentV2、状态管理和组件分层
前端
biubiubiu_LYQ14 小时前
萌新小白基础理解篇之 this 关键字
前端·javascript
光影少年14 小时前
Redux 中间件作用(redux-thunk/redux-saga)
前端·react.js·掘金·金石计划
爱上好庆祝14 小时前
学习JS第十一天(JS的进阶)
前端·javascript·学习