<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> 上设置 transition 和 keepalive 属性。如果你想定义一个特定的页面,可以在页面组件的 definePageMeta 中设置。
<Transition>,请确保该页面有一个单一的根元素。由于 <NuxtPage> 在底层使用了 <Suspense>,因此在页面更改期间组件生命周期行为与典型的 Vue 应用程序不同。
在典型的 Vue 应用程序中,新页面组件仅在前一个组件完全卸载后才挂载。然而,在 Nuxt 中,由于 Vue <Suspense> 的实现方式,新页面组件在卸载前一个组件之前就会挂载。
name: 告诉 <RouterView> 渲染在匹配路由记录的组件选项中具有相应名称的组件。stringroute: 具有所有已解析组件的路由位置。RouteLocationNormalizedpageKey: 控制 NuxtPage 组件何时重新渲染。string 或 functiontransition: 为使用 NuxtPage 组件渲染的所有页面定义全局过渡。boolean 或TransitionPropskeepalive: 控制使用 NuxtPage 组件渲染的页面的状态保留。boolean 或KeepAliveProps/pages 目录中找到的所有 Vue 组件文件,自动解析 name 和 route。例如,如果你传递一个从不改变的键,<NuxtPage> 组件将只渲染一次——首次挂载时。
<template>
<NuxtPage page-key="static" />
</template>
你还可以使用基于当前路由的动态键
<NuxtPage :page-key="route => route.fullPath" />
$route 对象,因为它可能会导致 <NuxtPage> 渲染带 <Suspense> 的页面时出现问题。另外,pageKey 可以通过 definePageMeta 从位于 /pages 目录中的 Vue 组件的 <script> 部分作为 key 值传递。
<script setup lang="ts">
definePageMeta({
key: route => route.fullPath,
})
</script>
要获取页面组件的 ref,通过 ref.value.pageRef 访问它
<script setup lang="ts">
const page = ref()
function logFoo () {
page.value.pageRef.foo()
}
</script>
<template>
<NuxtPage ref="page" />
</template>
<script setup lang="ts">
const foo = () => {
console.log('foo method called')
}
defineExpose({
foo,
})
</script>
<NuxtPage> 还接受你可能需要进一步向下传递的自定义 props。
例如,在下面的例子中,foobar 的值将传递给 NuxtPage 组件,然后再传递给页面组件。
<template>
<NuxtPage :foobar="123" />
</template>
我们可以在页面组件中访问 foobar prop
<script setup lang="ts">
const props = defineProps<{ foobar: number }>()
console.log(props.foobar) // Outputs: 123
如果你没有使用 defineProps 定义该 prop,任何传递给 NuxtPage 的 prop 仍然可以直接从页面 attrs 访问。
<script setup lang="ts">
const attrs = useAttrs()
console.log(attrs.foobar) // Outputs: 123
</script>