router:改造实现根据文件路径自动设置路由

This commit is contained in:
2021-02-05 11:11:25 +08:00
parent a5b3394703
commit 7732eee52d

View File

@@ -1,45 +1,58 @@
import { createRouter, createWebHashHistory } from "vue-router";
import Home from "../views/Home.vue";
import CA from "../views/CA.vue";
import CA_Index from "../views/CA/Index.vue";
import CA_User from "../views/CA/UserApply.vue";
import CA_Unit from "../views/CA/UnitApply.vue";
import CA_Unit_composition from "../views/CA/UnitApply.composition.vue";
const routes = [
{
path: "/",
name: "Home",
component: Home
},
{
path: "/CA",
component: CA,
name: "数字证书申领",
children: [
{
path: "",
component: CA_Index
},
{
path: "user",
component: CA_User,
name: "个人数字证书申领"
},
{
path: "unit",
component: CA_Unit,
name: "企业数字证书申领"
},
{
path: "composition",
component: CA_Unit_composition,
name: "企业数字证书申领新"
const files = require.context("@/views", true, /\.vue$/);
let pages = [];
const genRoutes = [];
const pathName = (route, idx) => {
if (idx == undefined) idx = route.length - 1;
let path = route[idx];
path = `${idx == 0 ? "/" : ""}${path}`;
if (path == "/Home") {
path = "/";
}
]
if (path == "Index") {
path = "";
}
];
return path;
};
const findRoute = routeArray => {
let routes = genRoutes;
let route = null;
for (let i = 0; i < routeArray.length - 1; i++) {
route = routes.find(p => p.path == pathName(routeArray, i));
if (route) routes = route.children || [];
}
return route;
};
files.keys().forEach(key => {
const r = key
.replace("./", "")
.replace(".vue", "")
.split("/")
.filter(k => k !== "");
pages.push({ route: r, component: files(key).default });
});
pages
.sort((a, b) => a.route.length - b.route.length)
.forEach(e => {
const route = findRoute(e.route);
let path = pathName(e.route);
if (!route) {
genRoutes.push({
path,
name: e.component.name,
component: e.component
});
} else {
route.children = route.children || [];
route.children.push({
path,
name: e.component.name,
component: e.component
});
}
});
const routes = [...genRoutes];
const router = createRouter({
history: createWebHashHistory(),
routes