使用多个 router-view 嵌套即可 Router-view 进行命名,在路由导航里进行路由命名选择即可,即可挂载到对应命名的 router-view 的位置
在一级路由下渲染的是组件 RandomTool. Vue 文件,所以二级路由页面即是在 RandomTool. Vue 文件里挂载,话句话说,router-view 需要放在 RandomTool. Vue 文件里
RandomTool. Vue 文件如下:
<div class="arco-main-content">
<div class="arco-main-header">
<a-button @click="goback" v-if="toggleMenuVisible" class="button">
<template #icon>
<IconHome />
</template>
</a-button>
<a-divider
v-if="toggleMenuVisible"
:size="2"
style="border-bottom-style: dotted"
/>
</div>
<router-view name="tool" v-if="!routerVisible"></router-view>
<div class="card" id="parentNode" v-if="routerVisible">
<Card :bordered="false" size="small">
<SearchLayout>
<SearchLayoutContent>
<ProCardList
:data="routes"
:column="2"
@itemClick="handleItemClick"
>
<template #item="{ item }">
<ProCardMeta :title="item.title">
<template #avatar>
<Avatar>{{ item.title[0] }}</Avatar>
</template>
</ProCardMeta>
</template>
</ProCardList>
</SearchLayoutContent>
</SearchLayout>
</Card>
</div>
</div>
进行动态路由添加,将某一文件下所有 vue 文件注册为路由,tool ()代表需要渲染到名为 tool 的 router-view 位置
主路由文件:router. Js
loadDynamicToolsPage(router, 'tools');
将某个文件下所有 vue 文件下动态注册到导航守卫里
import { Router } from 'vue-router';
export const loadDynamicToolsPage = function (router: Router, moduleStr = 'tools'): void {
/*
https://router.vuejs.org/zh/guide/advanced/dynamic-routing.html
动态路由的例子:
router.addRoute({ path: '/about', component: About })
*/
const routerObj: Router = router;
// const modules = import.meta.glob('./dir/*.js')
const viteModules = import.meta.glob('../*.vue');
// 重点: import.meta.glob 不支持动态加载
// const viteModules = import.meta.glob('@/pages/'+moduleStr+'/*.vue');
console.log(viteModules)
const viteModuleArr = [];
for (const path in viteModules) {
// path 的值为 /src/pages/vite/echartsPage.vue
// console.log(path, mod)
const length = path.lastIndexOf('/');
const filename = path.substring(length + 1).split('.')[0];
const routeOption = {
// path: '/vite/' + filename,
path: `/${moduleStr}`,
component: () => import('../../../views/writerPage.vue'),
children: [
{
path: `${filename}`,
name: `${filename}`,
components: {
tool: () => import(`../../../components/${moduleStr}/${filename}.vue`)
}
}
]
}
routerObj.addRoute(routeOption);
// router.getRoutes():获取一个包含所有路由记录的数组。
// console.log('routerObj.getRoutes', routerObj.getRoutes());
/*
重点:
如果新增加的路由与当前位置相匹配,就需要你用 router.push() 或 router.replace() 来手动导航,才能显示该新路由。
*/
routerObj.replace(routeOption.path)
}
};
最后路由跳转:
const handleItemClick = (item) => {
router.push(`/tools/${item.path}`);
routerVisible.value = false;
toggleMenuVisible.value = true;
};
发现路由跳转回来后,一级路由下的相关组件不刷新,数据空白
需要手动刷新一级 router-view 或者使用 router. Go (-1)进行返回,因为其可以保留数据