共计 2217 个字符,预计需要花费 6 分钟才能阅读完成。
项目场景:
项目场景:通过 vue3+elementPlus 的 menu 组件结合 router 路由属性实现动态侧边栏效果,实现侧边栏动态跟随着路由的变化。搜了很多文档,描述的都不够完整。
效果如下:
点击侧边栏路由同步跳转展示对应的页面
问题描述
- menuRoutes 就是路由中 routes 对应的数组进行了一次过滤。
- v-if 是对有子路由的进行展示子级,否则展示没有子级的 menu
- component 的 is 直接放了 icon 不展示,创建图标映射表包裹着就能展示了
具体代码如下:要在 menu 组件上加上 router 属性
menu 组件:
{{item.meta.title}}
{{item2.meta.title}}
{{item.meta.title}}
这里 icon 要进行引入,引入之后再放到图标映射表里面,再把 icon 组件进行包裹
import {
HomeFilled,
Lock,
Location,
Histogram,
UserFilled,
User,
Menu,
} from "@element-plus/icons-vue";
// 创建图标映射表
const iconComponents = {
Location,
HomeFilled,
Lock,
UserFilled,
User,
Histogram,
Menu,
// 添加其他图标组件映射
};
// 过滤掉不需要展示的路由,并调整 layout 的子路由
const menuRoutes = computed(() => {
// 获取所有路由
const routes = $router.options.routes;
// 过滤掉不需要展示的路由并展开 layout 子路由
const adjustedRoutes = routes.flatMap((route) => {
// 隐藏 'layout' 路由但展示其子路由作为一级路由
if (route.path === "/" && route.children) {return route.children.map((child) => ({
...child,
path: child.path,
meta: child.meta,
}));
}
// 如果路由设置为隐藏,则跳过
if (route.meta?.hidden) {return [];
}
return route;
});
return adjustedRoutes;
});
为了方便调试理解,我把整个 routes 路由代码放上来,
- 在 meta 里面的 hidden 来控制展示和隐藏,true 为隐藏,false 为展示
- title 就是 menu 上展示的字段
- icon 这里手动写上,必须在映射表方法写上和 import 引入
比如这里的 layout 是不需要展示的,但 layout 的子路由 home 又需要展示,就得 menuRoutes 进行计算属性那里过滤。
export const constantRoute = [
{
path: "/login",
component: () => import("@/views/login/index.vue"),
// component: login,
name: "login",
meta: {
title: '登录',
icon: "Edit",
hidden: true
}
},
{
path: "/",
component: () => import("@/layout/index.vue"),
name: "layout",
meta: {
title: 'layout',
hidden: true,
icon: 'Suitcase',
},
redirect: "/home",
children: [
{
path: "/home",
component: () => import("@/views/home/index.vue"),
meta: {
title: "首页",
hidden: false,
icon: "HomeFilled",
},
},
],
},
{
path: "/404",
component: () => import("@/views/404/index.vue"),
name: "404",
meta: {
title: '404',
hidden: true
}
},
// 权限管理
{
path: "/acl",
component: () => import("@/layout/index.vue"),
name: "Acl",
meta: {
title: '权限管理',
hidden: false,
icon: 'Lock'
},
children: [
{
path: "/user",
component: () => import("@/views/acl/user/index.vue"),
meta: {
title: '用户管理',
hidden: false,
icon: 'UserFilled'
},
},
{
path: "/role",
component: () => import("@/views/acl/role/index.vue"),
meta: {
title: '角色管理',
hidden: false,
icon: 'User'
},
},
{
path: "/permission",
component: () => import("@/views/acl/permission/index.vue"),
meta: {
title: '菜单管理',
hidden: false,
icon: 'Menu'
},
}
]
},
];
最后
最后在内容展示区要放 routerview,展示 layout 的子路由
原文地址: 通过 element-Plus 中 menu 和 router 的绑定,实现页面跳转,完整版
正文完