<NuxtPage>

<NuxtPage> 组件是展示位于 pages/ 目录中的页面所必需的。

<NuxtPage> 是一个内置组件,随 Nuxt 一同提供。它允许您展示位于 pages/ 目录中的顶级或嵌套页面。

<NuxtPage> 是一个封装自 Vue Router 的 <RouterView> 的组件。它应当用来替代 <RouterView>,因为前者会额外处理内部状态。否则,useRoute() 可能会返回不正确的路径。

<NuxtPage> 包含以下组件:

<template>
  <RouterView #default="{ Component }">
    <!-- 可选,当使用过渡时 -->
    <Transition>
      <!-- 可选,当使用 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> 的实现方式,新页面组件 会在前一个组件卸载之前被挂载。

Props

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

示例

例如,如果您传入一个永不更改的键,<NuxtPage> 组件将仅在首次挂载时渲染一次。

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

您还可以使用基于当前路由的动态键:

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

另外,pageKey 也可以通过 definePageMeta/pages 目录中的 Vue 组件的 <script> 部分以 key 值的形式传递。

pages/my-page.vue
<script setup lang="ts">
definePageMeta({
  key: route => route.fullPath
})
</script>
Read and edit a live example in Docs > Examples > Routing > Pages.

页面引用

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

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 方法被调用')
}

defineExpose({
  foo,
})
</script>

自定义 Props

<NuxtPage> 还接受自定义 props,您可能需要将其进一步传递到层次结构中。

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

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

我们可以在页面组件中访问 foobar 属性:

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

console.log(props.foobar) // 输出: 123

如果您没有使用 defineProps 定义该属性,仍然可以通过页面 attrs 直接访问传递给 NuxtPage 的任何属性:

pages/page.vue
<script setup lang="ts">
const attrs = useAttrs()
console.log(attrs.foobar) // 输出: 123
</script>
Read more in Docs > Guide > Directory Structure > Pages.