Files
djangoadmin-wiki/DjangoAdmin_FastAPI_AntdVue/zh/volume2/fe-router.md
T
2026-09-12 23:12:15 +08:00

140 lines
3.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 前端路由与菜单
前端路由定义页面的访问路径,菜单是路由的可视化展示。项目的路由和菜单由后端动态返回,前端只需注册路由组件映射。
## 路由配置
### 文件位置
路由配置文件按模块分组:
```
ui/src/router/routes/system.ts
```
### 添加路由
在 `system.ts` 中添加岗位管理的路由:
```typescript
{
path: '/system',
name: 'System',
component: Layout,
meta: { title: '系统管理', icon: 'setting' },
children: [
{
path: 'position',
name: 'Position',
component: () => import('/@/views/system/position/index.vue'),
meta: { title: '岗位管理' },
},
// ... 其他系统管理路由
],
}
```
### 路由字段说明
| 字段 | 说明 |
|:----|:----|
| `path` | 路由路径(子路由不带 `/`) |
| `name` | 路由名称(唯一标识) |
| `component` | 组件引用(懒加载) |
| `meta.title` | 菜单显示标题 |
| `meta.icon` | 菜单图标 |
### 路由懒加载
```typescript
component: () => import('/@/views/system/position/index.vue')
```
使用动态 `import()` 实现路由懒加载,访问时才加载组件代码,优化首屏加载速度。
## 后端菜单配置
路由的实际注册由后端菜单数据驱动。在「系统管理 → 菜单管理」中添加菜单节点:
| 字段 | 值 |
|:----|:----|
| 菜单名称 | 岗位管理 |
| 菜单类型 | 菜单(type=1) |
| 路由路径 | `/system/position` |
| 组件路径 | `system/position/index` |
| 菜单图标 | 选择合适图标 |
| 排序号 | 设置显示顺序 |
| 状态 | 启用 |
### 菜单数据返回格式
后端接口 `/api/v1/menu/list` 返回的菜单数据:
```json
{
"code": 0,
"data": [
{
"id": 10,
"name": "系统管理",
"parent_id": 0,
"path": "/system",
"component": "Layout",
"type": 1,
"icon": "setting",
"children": [
{
"id": 101,
"name": "岗位管理",
"parent_id": 10,
"path": "/system/position",
"component": "system/position/index",
"type": 1,
"icon": "post"
}
]
}
]
}
```
### 前端路由生成
前端在登录后请求菜单数据,动态生成路由:
```
登录成功 → 请求 /api/v1/menu/list → 生成动态路由 → 注册到 Vue Router → 渲染菜单
```
## 菜单与权限的关系
```
菜单管理
├── 系统管理(目录)
│ ├── 岗位管理(菜单)
│ │ ├── 岗位查询(权限)→ sys:position:page
│ │ ├── 岗位新增(权限)→ sys:position:add
│ │ ├── 岗位编辑(权限)→ sys:position:update
│ │ └── 岗位删除(权限)→ sys:position:delete
│ └── ...
└── ...
```
| 节点类型 | type | 作用 |
|:----|:----|:----|
| 目录 | 0 | 菜单分组,不对应页面 |
| 菜单 | 1 | 对应一个页面路由 |
| 权限 | 2 | 对应一个操作权限,不在菜单中显示 |
## 开发要点
1. **路由文件按模块分组**:`system.ts`、`content.ts` 等
2. **组件使用懒加载**:`() => import(...)`
3. **菜单数据由后端驱动**:前端只需注册组件映射
4. **组件路径与后端 `component` 字段对应**:如 `system/position/index`
5. **新增模块只需在对应分组路由文件中追加子路由**
## 总结
前端路由使用 Vue Router 4,菜单路由由后端动态返回,前端通过 `addRoute` 动态注册。路由守卫负责权限校验和登录状态检查,未登录自动跳转登录页。