Skip to content

RouterView 插槽 | Vue Router

理解 RouterView 插槽

<RouterView> 组件提供了一个强大的插槽机制,允许你自定义路由组件的渲染方式。虽然默认的 <router-view /> 在大多数情况下足够使用,但插槽为你提供了更高级的控制能力。

基本插槽用法

默认等价形式

简写形式(最常用):

html
<router-view />

插槽形式(功能等价):

html
<router-view v-slot="{ Component }">
  <component :is="Component" />
</router-view>

高级功能实现

1. 结合 KeepAlive

保持路由组件活跃状态,而不是 RouterView 本身:

html
<router-view v-slot="{ Component }">
  <keep-alive>
    <component :is="Component" />
  </keep-alive>
</router-view>

条件性 KeepAlive

html
<router-view v-slot="{ Component, route }">
  <keep-alive :include="cachedComponents">
    <component 
      :is="Component" 
      :key="route.fullPath"
    />
  </keep-alive>
</router-view>

2. 页面过渡动画

为路由切换添加平滑的过渡效果:

html
<router-view v-slot="{ Component, route }">
  <transition 
    :name="route.meta.transition || 'fade'"
    mode="out-in"
  >
    <component :is="Component" :key="route.path" />
  </transition>
</router-view>

3. KeepAlive 与 Transition 结合

html
<router-view v-slot="{ Component, route }">
  <transition name="fade" mode="out-in">
    <keep-alive :max="10">
      <component 
        :is="Component" 
        :key="route.fullPath"
      />
    </keep-alive>
  </transition>
</router-view>

插槽参数详解

RouterView 插槽提供以下参数:

Component

  • 类型: Component | undefined
  • 说明: 当前路由对应的组件
  • 使用: 通过 <component :is="Component" /> 渲染

route

  • 类型: RouteLocationNormalized
  • 说明: 标准化后的路由对象
  • 使用: 访问路由信息,如 route.path, route.meta

实际应用场景

场景 1:加载状态指示器

html
<router-view v-slot="{ Component, route }">
  <suspense>
    <template #default>
      <component :is="Component" :key="route.fullPath" />
    </template>
    <template #fallback>
      <div class="loading-container">
        <div class="spinner"></div>
        <p>页面加载中...</p>
      </div>
    </template>
  </suspense>
</router-view>

场景 2:错误边界处理

html
<router-view v-slot="{ Component, route }">
  <error-boundary>
    <component :is="Component" :key="route.fullPath" />
  </error-boundary>
</router-view>

场景 3:权限包装器

html
<router-view v-slot="{ Component, route }">
  <permission-wrapper :requires="route.meta.permission">
    <component :is="Component" />
  </permission-wrapper>
</router-view>

场景 4:布局系统

html
<router-view v-slot="{ Component, route }">
  <component 
    :is="getLayoutComponent(route)"
    :current-route="route"
  >
    <component :is="Component" />
  </component>
</router-view>

模板引用技巧

使用插槽可以让我们直接将模板引用放置在路由组件上:

html
<router-view v-slot="{ Component }">
  <component :is="Component" ref="mainContent" />
</router-view>

而如果我们将引用放在 <router-view> 上,那引用将会被 RouterView 的实例填充,而不是路由组件本身。

最佳实践

  1. 合理使用 key - 为动态组件添加合适的 key 属性
  2. 性能考虑 - 避免在插槽内进行复杂的计算
  3. 代码组织 - 将复杂的插槽逻辑提取到单独组件中

🚀 提示:RouterView 插槽为构建复杂的路由应用提供了强大的灵活性,合理使用可以大大提升应用的用户体验和可维护性。

🚀 Vue Router - 让前端路由变得简单而强大 | 构建现代化单页应用的最佳选择