<NuxtPage>

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

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

<NuxtPage> 是一个包装器,包装了来自 Vue Router 的 <RouterView>。它应该被用来替代 <RouterView>,因为前者额外关注内部状态。否则,useRoute() 可能会返回不正确的路径。

<NuxtPage> 包含以下组件:

<template>
  <RouterView #default="{ 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>,请确保页面只有一个根元素。

属性

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

示例

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

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

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

<NuxtPage :page-key="route => route.fullPath" />
在这里不要使用 $route 对象,因为它可能会导致 <NuxtPage> 如何使用 <Suspense> 渲染页面的问题。

或者,你也可以在 /pages 目录中 Vue 组件的 <script> 部分的 definePageMeta 函数中通过 key 值传递 pageKey

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.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>

自定义属性

<NuxtPage> 还接受您可能需要进一步传递到层次结构中的自定义属性。

例如,在下面的示例中,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) // Outputs: 123

如果您没有用 defineProps 定义 props,传递到 NuxtPage 的任何 props 仍然可以直接从页面的 attrs 访问:

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