问题由来
之前做了简易版qiankun demo,基座并没有应用路由,后来想到基座需要有自己的路由,比如Login,404等,而且子应用的路由需要展示在基座的layout(Home路由下)中,一番配置之后发现,跳转子路由的时候直接跳出了基座的home路由,而子应用的挂载又在Home路由下,子应用此时无处挂载,所以报错。
解决
- 路由注册
import { createWebHistory, createRouter } from 'vue-router'
const routes = [
{
path: '/login',
name: 'login',
component: () => import('@/views/login/index.vue')
},
{
path: '/',
component: () => import('@/views/home/index.vue')
},
{
path: '/home',
name: 'home', redirect: '/'
},
{
// 重点: 需要在基座路由中注册自用的路由
path: '/mfe/:mfeName*',
component: () => import('@/views/home/index.vue')
}
]
const router = createRouter({ history: createWebHistory(), routes: [ ...routes, ] })
export default router
- Home路由组件书写
// Home.vue
<template>
<div class="main">
<div class="main-header">
<el-menu mode="horizontal" router @select="handleSelect">
<el-menu-item index="/mfe/mfe-1"> Mfe-1 </el-menu-item>
<el-menu-item index="/mfe/mfe-2"> Mfe-2 </el-menu-item>
</el-menu>
</div>
<div class="main-container">
<div class="main-menu">
<el-menu router>
<el-menu-item :index="`${curApp}/home`"> home </el-menu-item>
<el-menu-item :index="`${curApp}/about`"> about </el-menu-item>
</el-menu> </div> <div class="container">
// 重点 // 当触发基座Home路由的子路由时,由<router-view />渲染
// 当触发子应用的路由时,拉取资源后由#CONTAINER挂载
<router-view />
<div id="CONTAINER"></div>
</div>
</div>
</div>
</template>
- qiankun start调用时机
// Home.vue 在Home组件挂载成功后调用start
<script setup>
import { onMounted } from 'vue'
import { start } from 'qiankun'
onMounted(() => { start() })
</script>