Vue3 + TypeScript + Ant Design Vue 实现左侧菜单动态配置与路由跳转(支持路由选中项同步 + 自动展开父菜单)
在后台管理系统开发中,左侧菜单是必不可少的功能模块。很多同学在用 Vue3 + TypeScript + Ant Design Vue 时,常常会遇到菜单 如何动态生成、如何和路由联动、如何保持展开项和选中项 等问题。本文将结合一个完整示例,带你一步步实现一个支持动态配置、支持选中项自动跟随路由、支持父菜单自动展开的左侧菜单。
一、项目准备
-
技术栈:Vue3 + TypeScript + Ant Design Vue + Vue Router
-
目标效果:
-
菜单配置由数组动态生成;
-
点击菜单自动路由跳转;
-
支持菜单折叠/展开;
-
选中项自动跟随路由,高亮正确显示;
-
父菜单自动展开,保证当前子路由显示正确;
-
支持多级子菜单。
-
二、实现代码
1. Menu 配置文件:菜单数据(通用模拟数据)
// menuData.ts
import {PieChartOutlined,FundViewOutlined,BranchesOutlined,CarOutlined
} from "@ant-design/icons-vue";
import { reactive, h } from "vue";export const menuData = reactive([{key: "/dashboard",icon: () => h(PieChartOutlined),label: "仪表盘",title: "dashboard",},{key: "/reports",icon: () => h(FundViewOutlined),label: "报表中心",title: "reports",},{key: "3",icon: () => h(CarOutlined),label: "资源管理",title: "resource",children: [{key: '/resource/create',label: '新增资源',title: 'create-resource',},{key: '/resource/list',label: '资源列表',title: 'resource-list',},{key: '/resource/settings',label: '资源设置',title: 'resource-settings',}]},{key: '4',icon: () => h(BranchesOutlined),label: '系统管理',title: 'system',children: [{key: '/system/users',label: '用户管理',title: 'system-users',},{key: '/system/roles',label: '角色