以下是 Vue Router(适用于 Vue 2 和 Vue 3 中的大多数配置)中常用的路由配置项,以及它们的作用说明:
由配置项常用属性及说明
| 属性名 |
类型 |
说明 |
path |
String |
路由路径,访问地址,例如 /login、/user/:id |
name |
String |
路由名称,配合 this.$router.push({ name: 'xxx' }) 使用 |
component |
Component |
路由对应的组件对象,支持 import() 懒加载 |
redirect |
String/Object |
重定向地址,如 { path: '/home' } 或 '/login' |
children |
Array |
嵌套路由,子路由配置数组 |
meta |
Object |
路由元信息,可自定义内容(如权限、标题、图标等) |
props |
Boolean/Object/Function |
将路由参数映射为组件 props(常用于复用组件) |
beforeEnter |
Function |
路由独享守卫,在进入该路由前执行 |
alias |
String/Array |
路由别名,访问 alias 时等价于访问原始 path |
caseSensitive |
Boolean |
是否区分大小写(默认 false) |
pathToRegexpOptions |
Object |
自定义 path-to-regexp 行为(如是否严格匹配 /) |
meta: {
title: '页面标题',
icon: 'home', // 左侧菜单图标
hidden: false, // 是否在菜单中隐藏
affix: true, // 是否固定在 tagsView 中
noCache: true, // 是否不被 keep-alive 缓存
roles: ['admin'], // 权限控制
breadcrumb: true, // 是否在面包屑中显示
activeMenu: '/xx/yy' // 高亮指定菜单
}
示例代码(常见配置组合)
{
path: '/dashboard',
name: 'Dashboard',
component: () => import('@/views/Dashboard'),
meta: {
title: '仪表盘',
icon: 'dashboard',
affix: true
}
}
{
path: '/user/:id',
name: 'UserDetail',
component: () => import('@/views/UserDetail'),
props: true, // 路由参数映射为 props
meta: {
title: '用户详情',
roles: ['admin', 'editor']
}
}
{
path: '/layout',
component: Layout,
children: [
{
path: 'profile',
component: () => import('@/views/Profile'),
name: 'UserProfile',
meta: { title: '用户中心' }
}
]
}
小结:最常用的属性
| 属性 |
用途 |
path |
定义访问路径 |
component |
指定要渲染的组件 |
name |
命名路由,利于跳转/缓存 |
meta |
页面元信息:标题、缓存、权限等 |
children |
嵌套路由 |
redirect |
路由重定向 |