1.因为这个面包屑在其他项目中可能也会用到,所以将其放在公共文件夹中
2.给这个组件设置一些属性
3.类型接口定义
export interface IBreadcrumb {
name: string
path?: string
}
4.在视图接收这些数据
5.在父组件进行使用
# 当前面包蟹是一个空数组,怎么获取当前面包屑的数组
1.首先我们可以使用这个工具函数:根据路径currentPath 路径匹配到最里面的菜单(menu);
就是type===2 的一个菜单,还需要拿到上一层type===1 时候的menu
//面包蟹工具
export function pathMapBreadcrumbs(userMenus: any[], currentPath: string):any{ const breadcrumbs:IBreadcrumb[]=[]
for (const menu of userMenus) {
if (menu.type === 1) {
//递归查找
const findMenu = pathMapToMenu(menu.children ?? [], currentPath)
// 找到就返回
if (findMenu) {
breadcrumbs.push({name:menu.name,path:menu.url})
breadcrumbs.push({name:findMenu.name,path:findMenu.url})
return findMenu
}
} else if (menu.type === 2 && menu.url === currentPath) {
return menu
}
}
return breadcrumbs //这样就可以拿到我们的breadcrumbs了
}
#这个文件夹里面的重复代码太多
1.可以合并为一个函数
export function pathMapBreadcrumbs(userMenus: any[], currentPath: string):any{
const breadcrumbs:IBreadcrumb[]=[]
pathMapToMenu(userMenus,currentPath,breadcrumbs) //直接调用就可以了
return breadcrumbs //这样就可以拿到我们的breadcrumbs了
}
export function pathMapToMenu(
userMenus: any[],
currentPath: string,
breadcrumbs?:IBreadcrumb[]
): any { //根据路径currrentPath路径匹配到最里面的菜单(menu)的:就是type 等于2 的一个菜单,还需要拿到上一层type===1 的时候的menu
//对菜单做一个遍历,
for (const menu of userMenus) {
if (menu.type === 1) {
//递归查找
const findMenu = pathMapToMenu(menu.children ?? [], currentPath)
// 找到就返回
if (findMenu) {
breadcrumbs?.push({name:menu.name,path:menu.url})
breadcrumbs?.push({name:findMenu.name,path:findMenu.url})
return findMenu
}
} else if (menu.type === 2 && menu.url === currentPath) {
return menu
}
}
}
export {firstMenu}
#在页面使用
1.代码展示
最终效果展示: