<NuxtPage>

源文件
<NuxtPage> 组件是显示 pages/ 目录下页面所必需的。

<NuxtPage> 是 Nuxt 内置的一个组件。它允许你显示位于 app/pages/ 目录下的顶层或嵌套页面。

<NuxtPage><RouterView>的包装器,它来自 Vue Router。你应该使用它来代替 <RouterView>,因为前者会额外处理内部状态。否则,useRoute() 可能会返回错误的路径。

<NuxtPage> 包含以下组件

<template>
  <RouterView v-slot="{ Component }">
    <!-- Optional, when using transitions -->
    <Transition>
      <!-- Optional, when using keep-alive -->
      <KeepAlive>
        <Suspense>
          <component :is="Component" />
        </Suspense>
      </KeepAlive>
    </Transition>
  </RouterView>
</template>

默认情况下,Nuxt 不启用 <Transition><KeepAlive>。你可以在 nuxt.config 文件中启用它们,或者通过在 <NuxtPage> 上设置 transitionkeepalive 属性来启用。如果你想定义特定页面,可以在页面组件中使用 definePageMeta 进行设置。

如果你在页面组件中启用了 <Transition>,请确保该页面只有一个根元素。

由于 <NuxtPage> 底层使用了 <Suspense>,因此页面切换时的组件生命周期行为与典型的 Vue 应用程序不同。

在典型的 Vue 应用程序中,新的页面组件仅在前一个页面完全卸载后才会挂载。然而,在 Nuxt 中,由于 Vue <Suspense> 的实现方式,新页面组件会在前一个组件卸载之前挂载。

属性

  • name:告诉 <RouterView> 渲染匹配路由记录的 components 选项中对应名称的组件。
    • 类型:string
  • route:所有组件均已解析的路由位置。
    • 类型:RouteLocationNormalized
  • pageKey:控制 NuxtPage 组件何时重新渲染。
    • 类型:stringfunction
  • transition:为所有使用 NuxtPage 组件渲染的页面定义全局过渡效果。
  • 类型:booleanTransitionProps
  • keepalive:控制使用 NuxtPage 组件渲染的页面的状态保持。
  • Nuxt 通过扫描并渲染 /pages 目录下的所有 Vue 组件文件,自动解析 nameroute

    示例

    例如,如果你传递一个从不改变的 key,<NuxtPage> 组件将只渲染一次——即首次挂载时。

    app/app.vue
    <template>
      <NuxtPage page-key="static" />
    </template>
    

    你也可以使用基于当前路由的动态 key

    <NuxtPage :page-key="route => route.fullPath" />
    
    在此处不要使用 $route 对象,因为它可能会导致 <NuxtPage> 在使用 <Suspense> 渲染页面时出现问题。

    或者,可以通过 /pages 目录中 Vue 组件的 <script> 部分中的 definePageMeta,将 pageKey 作为 key 值传递。

    app/pages/my-page.vue
    <script setup lang="ts">
    definePageMeta({
      key: route => route.fullPath,
    })
    </script>
    
    Docs > 4 X > Examples > Routing > Pages 中阅读并编辑实时示例。

    页面的 Ref

    要获取页面组件的 ref,请通过 ref.value.pageRef 访问它。

    app/app.vue
    <script setup lang="ts">
    const page = ref()
    
    function logFoo () {
      page.value.pageRef.foo()
    }
    </script>
    
    <template>
      <NuxtPage ref="page" />
    </template>
    
    my-page.vue
    <script setup lang="ts">
    const foo = () => {
      console.log('foo method called')
    }
    
    defineExpose({
      foo,
    })
    </script>
    

    自定义 Props

    <NuxtPage> 还接受你可能需要向下传递到层级结构中的自定义 props。

    例如,在下方的示例中,foobar 的值将被传递给 NuxtPage 组件,然后再传递给页面组件。

    app/app.vue
    <template>
      <NuxtPage :foobar="123" />
    </template>
    

    我们可以在页面组件中访问 foobar prop

    app/pages/page.vue
    <script setup lang="ts">
    const props = defineProps<{ foobar: number }>()
    
    console.log(props.foobar) // Outputs: 123
    

    如果你没有使用 defineProps 定义该 prop,传递给 NuxtPage 的任何 props 仍然可以直接从页面的 attrs 中访问。

    app/pages/page.vue
    <script setup lang="ts">
    const attrs = useAttrs()
    console.log(attrs.foobar) // Outputs: 123
    </script>
    
    阅读更多内容:文档 > 4 X > 目录结构 > App > Pages