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