<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> 上设置 transition 和 keepalive 属性。如果您想定义特定页面,可以在页面组件的 definePageMeta 中设置。
如果您在页面组件中启用
<Transition>,请确保该页面具有单个根元素。由于 <NuxtPage> 在底层使用了 <Suspense>,因此页面更改期间的组件生命周期行为与典型的 Vue 应用程序不同。
在典型的 Vue 应用程序中,新的页面组件仅在之前的页面组件完全卸载 之后 才会被挂载。但是,在 Nuxt 中,由于 Vue <Suspense> 的实现方式,新的页面组件会在之前的页面组件卸载 之前 被挂载。
属性
name:告诉<RouterView>在匹配的路由记录的 components 选项中渲染具有相应名称的组件。- 类型:
string
- 类型:
route:已解析所有组件的路由位置。- 类型:
RouteLocationNormalized
- 类型:
pageKey:控制NuxtPage组件何时重新渲染。- 类型:
string或function
- 类型:
transition:为使用NuxtPage组件渲染的所有页面定义全局过渡效果。- 类型:
boolean或TransitionProps
- 类型:
keepalive:控制使用NuxtPage组件渲染的页面的状态保持。- 类型:
boolean或KeepAliveProps
- 类型:
Nuxt 通过扫描和渲染在
/pages 目录中找到的所有 Vue 组件文件,自动解析 name 和 route。示例
例如,如果您传递一个永不更改的键,则 <NuxtPage> 组件将仅渲染一次 - 在首次挂载时。
app.vue
<template>
<NuxtPage page-key="static" />
</template>
您还可以使用基于当前路由的动态键
<NuxtPage :page-key="route => route.fullPath" />
请勿在此处使用
$route 对象,因为它可能会导致 <NuxtPage> 使用 <Suspense> 渲染页面时出现问题。或者,可以通过 <script> 部分中的 definePageMeta 从 Vue 组件将 pageKey 作为 key 值传递到 /pages 目录中。
pages/my-page.vue
<script setup lang="ts">
definePageMeta({
key: route => route.fullPath
})
</script>
在 文档 > 示例 > 路由 > 页面 中阅读和编辑实时示例。
页面的 Ref
要获取页面组件的 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 method called')
}
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 定义属性,那么传递给 NuxtPage 的任何属性仍然可以直接从页面 attrs 访问
pages/page.vue
<script setup lang="ts">
const attrs = useAttrs()
console.log(attrs.foobar) // Outputs: 123
</script>