创建一个路由列表,类似网站地图索引了所有页面的路径
const routes = [
// ===== 主路由:集中展示常用参数 =====
{
path: '/user/:id', // 路径(必填)
name: 'user', // 命名路由(用于编程式导航)
component: () => import('@/views/User.vue'), // 懒加载组件
props: true, // 将 params.id 作为 prop
meta: { requiresAuth: true, title: '用户' }, // 自定义元数据
alias: ['/profile', '/me'], // 多个别名(数组)
beforeEnter: (to, from) => { // 路由独享守卫
if (to.params.id > 0) return true
return { name: 'not-found' }
}
},
// ===== 辅助路由:展示 redirect(与 component 互斥,单独写) =====
{
path: '/old-user',
redirect: { name: 'user' } // 重定向到命名路由
}
]说明:
redirect和component不能同时存在,所以单独列一条路由。除此之外,所有常用参数都集中在第一条路由里。
参数
| 参数 | 类型 | 关键用法 |
|---|---|---|
| path | string | URL 路径,支持 :param 动态参数 |
| name | string | 命名路由,配合 router.push({ name }) 使用 |
| component | Component | 支持 () => import() 懒加载 |
| props | boolean/object/function | 将路由参数转为组件 props(解耦) |
| meta | object | 存储权限、标题等自定义数据 |
| alias | string/array | 多个 URL 访问同一组件(支持数组) |
| beforeEnter | function/array | 路由独享守卫(可传数组依次执行) |
| redirect | string/object/function | 重定向,可与 component 互斥 |
| children | array | 嵌套路由(子路径不加 /) |
| components | object | 命名视图(多 router-view) |
| caseSensitive | boolean | 路径大小写敏感(默认 false) |
| pathToRegexpOptions | object | 尾部斜杠严格匹配等高级配置 |