<NuxtPage>
<NuxtPage> 组件是展示 pages/ 目录中页面所必需的。
<NuxtPage>
是 Nuxt 内置的组件,用于展示位于pages/
目录中的顶级或嵌套页面。
<NuxtPage>
是对 Vue Router 的 <RouterView>
的封装。应使用 <NuxtPage>
而不是 <RouterView>
,因为前者会额外处理内部状态。否则,useRoute()
可能返回错误的路径。<NuxtPage>
包含以下组件:
<template>
<RouterView #default="{ Component }">
<!-- 可选,用于过渡效果 -->
<Transition>
<!-- 可选,用于保持组件状态 -->
<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>
渲染与匹配路由记录的组件选项中对应名称的组件。- 类型:
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>
渲染页面时出现问题。或者,pageKey
可以通过 /pages
目录中 Vue 组件的 <script>
部分使用 definePageMeta
传递为 key
值。
pages/my-page.vue
<script setup lang="ts">
definePageMeta({
key: route => route.fullPath
})
</script>
阅读并编辑实时示例中的内容 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>
自定义属性
<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) // 输出:123
如果您未使用 defineProps
定义属性,传递给 NuxtPage
的任何属性仍可直接从页面 attrs
中访问:
pages/page.vue
<script setup lang="ts">
const attrs = useAttrs()
console.log(attrs.foobar) // 输出:123
</script>