refactor: 优化代码规范和可读性
This commit is contained in:
@@ -15,56 +15,72 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { RouteLocationMatched } from "vue-router";
|
||||
import type { RouteLocationMatched } from "vue-router";
|
||||
import { compile } from "path-to-regexp";
|
||||
import router from "@/router";
|
||||
import { translateRouteTitle } from "@/lang/utils";
|
||||
|
||||
type BreadcrumbRoute = {
|
||||
path: string;
|
||||
name?: RouteLocationMatched["name"];
|
||||
redirect?: string;
|
||||
meta: RouteLocationMatched["meta"];
|
||||
};
|
||||
|
||||
const currentRoute = useRoute();
|
||||
// 默认补一个首页面包屑
|
||||
const dashboardRoute: BreadcrumbRoute = { path: "/dashboard", meta: { title: "dashboard" } };
|
||||
|
||||
// 根据当前路由参数生成跳转路径
|
||||
const pathCompile = (path: string) => {
|
||||
const { params } = currentRoute;
|
||||
const toPath = compile(path);
|
||||
return toPath(params);
|
||||
};
|
||||
|
||||
const breadcrumbs = ref<Array<RouteLocationMatched>>([]);
|
||||
const breadcrumbs = ref<BreadcrumbRoute[]>([]);
|
||||
|
||||
// 生成面包屑列表
|
||||
function getBreadcrumb() {
|
||||
let matched = currentRoute.matched.filter((item) => item.meta && item.meta.title);
|
||||
let matched: BreadcrumbRoute[] = currentRoute.matched
|
||||
.filter((item) => item.meta && item.meta.title)
|
||||
.map(({ path, name, redirect, meta }) => ({
|
||||
path,
|
||||
name,
|
||||
redirect: typeof redirect === "string" ? redirect : undefined,
|
||||
meta,
|
||||
}));
|
||||
|
||||
const first = matched[0];
|
||||
if (!isDashboard(first)) {
|
||||
matched = [{ path: "/dashboard", meta: { title: "dashboard" } } as any].concat(matched);
|
||||
matched = [dashboardRoute].concat(matched);
|
||||
}
|
||||
breadcrumbs.value = matched.filter((item) => {
|
||||
return item.meta && item.meta.title && item.meta.breadcrumb !== false;
|
||||
});
|
||||
}
|
||||
|
||||
function isDashboard(route: RouteLocationMatched) {
|
||||
const name = route && route.name;
|
||||
// 判断是否为首页路由
|
||||
function isDashboard(route?: BreadcrumbRoute) {
|
||||
const name = route?.name;
|
||||
if (!name) {
|
||||
return false;
|
||||
}
|
||||
return name.toString().trim().toLocaleLowerCase() === "Dashboard".toLocaleLowerCase();
|
||||
}
|
||||
|
||||
function handleLink(item: any) {
|
||||
// 处理面包屑跳转
|
||||
function handleLink(item: BreadcrumbRoute) {
|
||||
const { redirect, path } = item;
|
||||
if (redirect) {
|
||||
router.push(redirect).then(
|
||||
() => {},
|
||||
(err) => {
|
||||
console.warn(err);
|
||||
}
|
||||
);
|
||||
router.push(redirect).catch((err) => {
|
||||
console.warn(err);
|
||||
});
|
||||
return;
|
||||
}
|
||||
router.push(pathCompile(path)).then(
|
||||
() => {},
|
||||
(err) => {
|
||||
console.warn(err);
|
||||
}
|
||||
);
|
||||
router.push(pathCompile(path)).catch((err) => {
|
||||
console.warn(err);
|
||||
});
|
||||
}
|
||||
|
||||
watch(
|
||||
|
||||
Reference in New Issue
Block a user