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>
相关推荐
J船长1 小时前
从 App 开发到 Unity 游戏开发:建立认知地图,结合 AI 开始实践
前端
牛奔1 小时前
mise 管理多版本 Go 项目
开发语言·前端·chrome·后端·golang
能源革命2 小时前
Vue 网格拖拽布局组件全景指南:7 大方案深度对比
前端·javascript·vue.js
PC2005_cloud3 小时前
AI 汉字漂移实录:它为什么总把「学习」写成日语「学習」
前端·后端
穆梓兰煊3 小时前
AI供应链安全不再只是包安全,还涉及模型与数据
前端·数据库
RaaS1003 小时前
AI网关能做Prompt注入防护吗?AI网关核心功能详解
前端·后端
deli0073 小时前
Skill 怎么写才被 Agent 命中?18 条规则做成 SKILL.md 校验器,规范样例 92 分
前端
Hum8le3 小时前
CTF题目《easy_web》(安洵杯 2019 变种 Web)
前端·安全·web安全
coding漫漫长路3 小时前
二值化后还剩1212个黑点,OCR却认成了乱码
前端