如图路由配置
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{ path: '/login', component: () => import('@/views/login/LoginPage.vue') }, // 登录页
{
path: '/',
component: () => import('@/views/layout/LayoutContainer.vue'),
redirect: '/article/manage',
children: [
{
path: '/article/manage',
component: () => import('@/views/article/ArticleManage.vue')
},
{
path: '/article/channel',
component: () => import('@/views/article/ArticleChannel.vue')
},
{
path: '/user/profile',
component: () => import('@/views/user/UserProfile.vue')
}
]
}
]
})
1、routes:
这是一个数组,每个对象都是一个路由
2、登录页路由:
{ path: '/login', component: () => import('@/views/login/LoginPage.vue') }, // 登录页
当访问/login
路径时,会加载并显示@/views/login/LoginPage.vue
这个组件。这里的@
符号通常是一个别名,指向项目的src
目录。
3、主布局路由
{
path: '/',
component: () => import('@/views/layout/LayoutContainer.vue'),
redirect: '/article/manage',
children: [...]
}
- 这个是重点,path:' / ' , 表示根目录,比如:localhost:8080/,当我们访问根目录的时候,
- 会加载这个路由:
component: () => import('@/views/layout/LayoutContainer.vue')
- 加载并显示
LayoutContainer.vue
这个组件作为主布局。 - 为什么说是作为主布局呢?因为它有子路由,也就是这个:children: [...]
- 回到我们刚开始的路由文件,可以看到它有三个子路由,我给大家展示一张图就知道了
可以看到这个页面左边就是菜单栏,我们点击收藏、笔记这些的时候菜单栏是不变的,变化的是右边。左边就是主布局。
4、redirect: '/article/manage' 重定向
这是一个重定向,意思是只要访问根目录,那么就直接重定向到这个路由: '/article/manage'
从第一张图可以看到,这个路由是属于根目录的子路由,也就是说,当我们访问根目录的时候,会先加载主布局组件LayoutContainer.vue,然后重定向到子路由 /article/manage,加载ArticleManage.vue组件
5、重定向的路由不是当前路由的子路由,会不会加载主布局组件呢?
答案是不会
假如路由是这样写的,访问根目录 localhost:8080 的时候就直接跳转ArticleManage.vue组件,不会加载主布局组件
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/login',
component: () => import('@/views/login/LoginPage.vue') // 登录页
},
{
path: '/article/manage',
component: () => import('@/views/article/ArticleManage.vue') // 文章管理页
},
{
path: '/',
component: () => import('@/views/layout/LayoutContainer.vue'),
redirect: '/article/manage',
children: [
// 其他子路由...
]
}
// 其他路由...
]
})