<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>
的實作方式,新的頁面元件會在前一個元件卸載之前掛載。
Props
name
:告知<RouterView>
在比對路由記錄的 components 選項中,渲染具有對應名稱的元件。- type:
string
- type:
route
:已解析其所有元件的路由位置。- type:
RouteLocationNormalized
- type:
pageKey
:控制NuxtPage
元件何時重新渲染。- type:
string
或function
- type:
transition
:為使用NuxtPage
元件渲染的所有頁面定義全域轉場效果。- type:
boolean
或TransitionProps
- type:
keepalive
:控制使用NuxtPage
元件渲染的頁面的狀態保留。- type:
boolean
或KeepAliveProps
- type:
Nuxt 會透過掃描和渲染在
/pages
目錄中找到的所有 Vue 元件檔案,自動解析 name
和 route
。範例
例如,如果您傳遞一個永遠不會變更的 key,則 <NuxtPage>
元件只會渲染一次 - 在第一次掛載時。
app.vue
<template>
<NuxtPage page-key="static" />
</template>
您也可以使用基於目前路由的動態 key
<NuxtPage :page-key="route => route.fullPath" />
請勿在此處使用
$route
物件,因為它可能會導致 <NuxtPage>
使用 <Suspense>
渲染頁面時發生問題。或者,pageKey
可以透過 Vue 元件 <script>
區段中 definePageMeta
以 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>
自訂 Props
<NuxtPage>
也接受您可能需要進一步向下層次傳遞的自訂 props。
例如,在以下範例中,foobar
的值將傳遞到 NuxtPage
元件,然後傳遞到頁面元件。
app.vue
<template>
<NuxtPage :foobar="123" />
</template>
我們可以在頁面元件中存取 foobar
prop
pages/page.vue
<script setup lang="ts">
const props = defineProps<{ foobar: number }>()
console.log(props.foobar) // Outputs: 123
如果您尚未透過 defineProps
定義 prop,則任何傳遞到 NuxtPage
的 props 仍然可以直接從頁面 attrs
存取
pages/page.vue
<script setup lang="ts">
const attrs = useAttrs()
console.log(attrs.foobar) // Outputs: 123
</script>