主路由、子路由、重定向的关系

文章详细描述了在Vue应用中使用createRouter创建路由表的过程,重点介绍了主布局(LayoutContainer.vue)和重定向的用法。登录页、主路由(重定向到/article/manage)以及子路由的结构清晰展现。
摘要由CSDN通过智能技术生成

 如图路由配置

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: [...]  
}
  1. 这个是重点,path:' / ' , 表示根目录,比如:localhost:8080/,当我们访问根目录的时候,
  2. 会加载这个路由:component: () => import('@/views/layout/LayoutContainer.vue')
  3. 加载并显示LayoutContainer.vue这个组件作为主布局
  4. 为什么说是作为主布局呢?因为它有子路由,也就是这个:children: [...] 
  5. 回到我们刚开始的路由文件,可以看到它有三个子路由,我给大家展示一张图就知道了

可以看到这个页面左边就是菜单栏,我们点击收藏、笔记这些的时候菜单栏是不变的,变化的是右边。左边就是主布局。


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: [  
        // 其他子路由...  
      ]  
    }  
    // 其他路由...  
  ]  
})

  • 9
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值