Skip to content

Commit

Permalink
refactor: 重构路由
Browse files Browse the repository at this point in the history
  • Loading branch information
jsxiaosi committed Jun 25, 2022
1 parent 77a7502 commit 9301305
Show file tree
Hide file tree
Showing 22 changed files with 307 additions and 201 deletions.
50 changes: 25 additions & 25 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -86,34 +86,34 @@
</div>
<script>
// 此代码仅用于开发环境的友好提示,项目打包前请去掉这段js代码 This code is only used as a friendly reminder of the development environment, please remove this js code before packaging the project
window.onload = function () {
(function () {
const ua = navigator.userAgent.toLowerCase();
const re = /(msie|firefox|chrome|opera|version).*?([\d.]+)/;
const m = ua.match(re);
const Sys = {
browser: m[1].replace(/version/, "'safari"),
version: m[2],
};
// window.onload = function () {
// (function () {
// const ua = navigator.userAgent.toLowerCase();
// const re = /(msie|firefox|chrome|opera|version).*?([\d.]+)/;
// const m = ua.match(re);
// const Sys = {
// browser: m[1].replace(/version/, "'safari"),
// version: m[2],
// };

const browser = Array.of('chrome', 'firefox').includes(Sys.browser);
const version = parseFloat(Sys.version);
// const browser = Array.of('chrome', 'firefox').includes(Sys.browser);
// const version = parseFloat(Sys.version);

const el = document.querySelector('.develop');
// const el = document.querySelector('.develop');

if (el) {
if (browser && version >= 90) {
let success = document.createTextNode('哈哈哈哈哈!帅吧? 😃');
el.appendChild(success);
} else {
let warn = document.createTextNode('你这浏览器不行啊,换一个吧!😯');
el.appendChild(warn);
el.style.color = 'red';
}
}
return Sys;
})();
};
// if (el) {
// if (browser && version >= 90) {
// let success = document.createTextNode('哈哈哈哈哈!帅吧? 😃');
// el.appendChild(success);
// } else {
// let warn = document.createTextNode('你这浏览器不行啊,换一个吧!😯');
// el.appendChild(warn);
// el.style.color = 'red';
// }
// }
// return Sys;
// })();
// };
</script>
<script type="module" src="/src/main.ts"></script>
</body>
Expand Down
10 changes: 2 additions & 8 deletions mock/demo/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,7 @@ import { MockMethod, Recordable } from 'vite-plugin-mock';
const power = [
{
path: '/welcome',
name: 'RtHome',
children: [
{
path: '',
name: 'RtWelcome',
},
],
name: 'RtWelcome',
},
{
path: '/components',
Expand Down Expand Up @@ -133,7 +127,7 @@ const adminRoute = [
children: [
{
path: 'menu1-2-1',
name: 'RtMenu1-2',
name: 'RtMenu1-2-1',
},
{
path: 'menu1-2-2',
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"lodash-es": "^4.17.21",
"marked": "^4.0.17",
"mockjs": "^1.1.0",
"path": "^0.12.7",
"pinia": "^2.0.14",
"sortablejs": "^1.15.0",
"vue": "^3.2.37",
Expand Down Expand Up @@ -76,7 +77,6 @@
"http-server": "^14.1.1",
"husky": "^8.0.1",
"lint-staged": "^13.0.1",
"path": "^0.12.7",
"postcss-html": "^1.4.1",
"postcss-import": "^14.1.0",
"prettier": "2.6.2",
Expand Down
28 changes: 0 additions & 28 deletions src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -9,32 +9,4 @@
import { deffElementLocale } from '@/hooks/web/useI18n';
const { tolocale } = deffElementLocale();
// import { deffHttp } from './utils/axios';
// import HelloWorld from './components/HelloWorld.vue'
// const admin = 'asdasdasdas'
// This starter template is using Vue 3 experimental <script setup> SFCs
// Check out https://github.com/vuejs/rfcs/blob/script-setup-2/active-rfcs/0000-script-setup.md
// store.commit($mutation.SET_COLLAPSEMENU, locMenu)
// const req = async () => {
// const res = await deffHttp.post<void>({ url: '/mock_api/login',data:{username:'admin',password:'123123'} })
// console.log(res)
// }
// const req2 = async () => {
// const res = await deffHttp.get<void>(
// {
// url: '/mock_api/getUserInfo',
// },
// {
// urlPrefix: 'https://xiaosisi.com',
// specialToken: 'asdasdasdasd',
// },
// );
// console.log(res);
// };
// req2();
</script>
4 changes: 2 additions & 2 deletions src/layouts/pageLayouts/components/AppMain/index.vue
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<template>
<section class="app-main">
<router-view>
<template #default="{ Component }">
<template #default="{ Component, route }">
<transition name="fade-transform" mode="out-in">
<keep-alive :include="getInclude">
<component :is="Component"></component>
<component :is="Component" :key="route.fullPath"></component>
</keep-alive>
</transition>
</template>
Expand Down
34 changes: 24 additions & 10 deletions src/layouts/pageLayouts/components/Breadcrumb/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@
<span
v-if="item.redirect === 'noRedirect' || index == levelList.length - 1"
class="no-redirect"
>{{ t(`${item.meta.title}`) }}</span
>{{ t(`${item.meta?.title}`) }}</span
>
<a v-else class="redirect" @click.prevent="handleLink(item)">
{{ t(`${item.meta.title}`) }}
{{ t(`${item.meta?.title}`) }}
</a>
</el-breadcrumb-item>
</transition-group>
Expand All @@ -30,31 +30,44 @@

<script setup lang="ts">
import SvgIcon from '@/components/SvgIcon/index.vue';
import type { RouteLocationMatched } from 'vue-router';
import { ref, watch } from 'vue';
import { getAppCollapseMenu } from '@/hooks/userAppWindow';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from '@/hooks/web/useI18n';
import { useAppStore } from '@/store/modules/app';
import { AppRouteRecordRaw } from '#/route';
import { getParentPaths, findRouteByPath } from '@/router/utils';
const { t } = useI18n();
const levelList = ref<Array<RouteLocationMatched>>([]);
const levelList = ref<Array<AppRouteRecordRaw>>([]);
// 获取路由配置
const router = useRouter();
// 当前路由
const route = useRoute();
const routes = router.options.routes as AppRouteRecordRaw[];
// 解析路由匹配的数组
const getBreadcrumb = () => {
// 过滤留下只有meta和title
const matched: RouteLocationMatched[] = route.matched.filter(
(item) => item.meta && item.meta.title,
);
// 拼出最终需要展示的跳转数据
const matched: AppRouteRecordRaw[] = [];
const parentRoutes = getParentPaths(router.currentRoute.value.name || '', routes);
// 获取每个父级路径对应的路由信息
parentRoutes.forEach((path) => {
if (path !== '/') {
matched.push(findRouteByPath(path, routes) as AppRouteRecordRaw);
}
});
const item = route.matched.find(
(item) => route.name === item.name,
) as unknown as AppRouteRecordRaw;
matched.push(item);
levelList.value = matched.filter(
(item) => item.meta && item.meta.title && item.meta.breadcrumb !== false,
(item) => item.meta && item.meta.title && !item.meta.breadcrumb,
);
};
// 手动解析path中可能存在的参数
const pathCompile = (path: any) => {
const toPath = path;
Expand All @@ -67,6 +80,7 @@
router.push(redirect);
return;
}
// console.log();
router.push(pathCompile(path));
};
// 首次调用
Expand Down
1 change: 0 additions & 1 deletion src/layouts/pageLayouts/components/Sidebar/MinSidebar.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
:active="activeMenyu"
class="horizontal-header-menu"
mode="horizontal"
router
>
<app-link
v-for="menusRoute in usePermissionStoreHook().wholeMenus"
Expand Down
24 changes: 11 additions & 13 deletions src/layouts/pageLayouts/components/Sidebar/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
:key="menuRoute.path"
:item="menuRoute"
:is-nest="false"
:base-path="menuRoute.basePath || menuRoute.path"
:base-path="menuRoute.path"
/>
</el-menu>
</el-scrollbar>
Expand All @@ -35,34 +35,32 @@
},
});
let subMenuData = ref(usePermissionStoreHook().wholeMenus);
let subMenuData = ref<AppRouteRecordRaw[]>(usePermissionStoreHook().wholeMenus);
const menuData = computed<AppRouteRecordRaw[]>(() => {
return appConfigMode.value.sidebarMode === 'blend'
? subMenuData.value
: usePermissionStoreHook().wholeMenus;
});
function getSubMenuData(path: RouteRecordName) {
function getSubMenuData(name: RouteRecordName) {
console.log('不执行了是吗?');
// path的上级路由组成的数组
const parentPathArr = getParentPaths(path, usePermissionStoreHook().wholeMenus);
const parentPathArr = getParentPaths(name, usePermissionStoreHook().wholeMenus);
// 当前路由的父级路由信息
const parenetRoute = findRouteByPath(
parentPathArr[0] || path,
parentPathArr[0] || name,
usePermissionStoreHook().wholeMenus,
);
if (!parenetRoute?.children) return;
let children = parenetRoute.children;
children = children.map((i: AppRouteRecordRaw) => {
i.basePath = parentPathArr[0] + '/' + i.path;
return i;
});
subMenuData.value = children;
if (parenetRoute) {
if (parenetRoute.children) subMenuData.value = parenetRoute.children;
else subMenuData.value = [parenetRoute];
}
}
getSubMenuData(route.name as RouteRecordName);
watch(
() => route.path,
() => [route.path, appConfigMode.value.sidebarMode],
() => {
if (appConfigMode.value.sidebarMode === 'blend') {
getSubMenuData(route.name as RouteRecordName);
Expand Down
8 changes: 4 additions & 4 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,16 @@ import '@/styles/index.scss';

const app = createApp(App);

getServerConfig().then((_config) => {
getServerConfig().then(async (_config) => {
// 路由
await configMainRouter(app);

// 全局钩子
configMainGlobalProperties(app);

// Vuex
configMainStore(app);

// 路由
configMainRouter(app);

// 国际化
configMainI18n(app);

Expand Down
20 changes: 3 additions & 17 deletions src/router/index.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,17 @@
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import { App } from 'vue';
import { AppRouteRecordRaw } from '#/route';
import routeModuleList from './modules';
import { handleAliveRoute, initAsyncRoute } from './utils';
import { usePermissionStoreHook } from '@/store/modules/permission';

const routes: Array<AppRouteRecordRaw> = [
...routeModuleList, // 管理端
{
path: '/',
// redirect: routeModuleList[0].path,
name: '/',
},
{
path: '/login',
component: () => import('@/views/login/index.vue'),
name: 'login',
},
];
// console.log(routes)
export const router = createRouter({
history: createWebHistory(''),
routes: routes as unknown as RouteRecordRaw[],
routes: routeModuleList as unknown as RouteRecordRaw[],
});

export const configMainRouter = (app: App<Element>) => {
export const configMainRouter = async (app: App<Element>) => {
app.use(router);
await router.isReady();
};

// 路由守卫
Expand Down
39 changes: 31 additions & 8 deletions src/router/modules/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,36 @@
import { AppRouteRecordRaw } from '#/route';
import { pathNamekeyCheck, setUpRoutePath } from '../utils';

const modules = import.meta.globEager('./**/*.ts');
function configRouteList() {
// 白名单目录/文件
const whiteCatalogue = ['root', 'whiteList'];

const routeModuleList: AppRouteRecordRaw[] = [];
let routeModulesList: AppRouteRecordRaw[] = []; //菜单路由
const whiteRouteModulesList: AppRouteRecordRaw[] = []; // 不参与菜单处理的路由

Object.keys(modules).forEach((key) => {
const mod = modules[key].default || {};
const modList = Array.isArray(mod) ? [...mod] : [mod];
routeModuleList.push(...modList);
});
// 自动查找路由配置文件
const modules = import.meta.globEager('./**/*.ts');
Object.keys(modules).forEach((key) => {
const mod = modules[key].default;
if (!mod) return;
const modList = Array.isArray(mod) ? [...mod] : [mod];
if (pathNamekeyCheck(key, whiteCatalogue)) {
whiteRouteModulesList.push(...modList);
} else {
routeModulesList.push(...modList);
}
});

export default routeModuleList;
// 菜单路由 根据父级重新处理子路由的path路径
routeModulesList = setUpRoutePath(routeModulesList);

// 先把菜单路由插入根路径 '/' 防止route 初始化警告查找不到路由
const whIndex = whiteRouteModulesList.findIndex((i) => i.path === '/');
whiteRouteModulesList[whIndex]['children'] = routeModulesList;
return { whiteRouteModulesList, routeModulesList };
}

const { whiteRouteModulesList, routeModulesList } = configRouteList();

export default whiteRouteModulesList;
export const sidebarRouteList = routeModulesList;
Loading

0 comments on commit 9301305

Please sign in to comment.