问题是这样的:

http://localhost:5173/index
假如我的这个页面是一个架子,顶部和侧边栏有内容,主内容是routerview占位
那么我刚打开http://localhost:5173/index的时候,routerView那块的内容不就
是空白了吗,所以这里一般都是怎么处理的,下面总结两种方式


空白路由页面.png

1. 默认重定向(常见)

在路由配置中,可以为父路由(如 /index)设置一个默认重定向,让它自动跳转到某个子路由(例如 /index/home)。这样,当访问 /index 时,会自动加载默认子页面。

// router/index.js 或 router 配置文件中
const routes = [
  {
    path: '/index',
    component: () => import('@/layouts/IndexLayout.vue'),
    redirect: '/index/home', // 自动重定向到默认子路由
    children: [
      {
        path: 'home', // 最终路径为 /index/home
        name: 'home',
        component: () => import('@/views/Home.vue')
      },
      // 其它子路由
    ]
  },
  // 其它路由
]

export default createRouter({
  history: createWebHistory(),
  routes
})

说明: 当用户首次访问 /index 时,会立即跳转到 /index/home,这样 <router-view> 中就会有内容展示。


2. 空路径子路由

另一种方式是在父路由的子路由中添加一个路径为空的路由,这样当访问 /index 时,也会自动加载该子路由的组件。

const routes = [
  {
    path: '/index',
    component: () => import('@/layouts/IndexLayout.vue'),
    children: [
      {
        path: '', // 空路径,相当于默认子路由
        name: 'default',
        component: () => import('@/views/Home.vue')
      },
      {
        path: 'home', // 也可以设置其他子路由
        name: 'home',
        component: () => import('@/views/Home.vue')
      },
      // 其它子路由
    ]
  },
  // 其它路由
]

说明: 这种方式无需重定向,直接在父路由内配置一个空路径的子路由,使得 <router-view> 在首次加载时就有内容显示,适合只显示一次的内容。


总结

  • 默认重定向:适用于需要明确跳转到某个子路由的场景,配置简单明了。
  • 空路径子路由:适用于希望 /index 本身就能加载默认内容的场景,无需额外跳转。

一般来说个人推荐使用默认重定向方式,因为它能更直观地展示页面的默认入口,并便于后续维护和扩展,如果有部分内容只显示一次的业务需求可以选择第二种方式。

最后修改:2025 年 03 月 25 日 09 : 57 AM
如果觉得此文章有用,请随意打赏