<NuxtPage>

原始檔
需要 <NuxtPage> 元件來顯示位於 pages/ 目錄中的頁面。

<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> 上設定 transitionkeepalive 屬性。如果你想定義一個特定的頁面,可以在頁面元件的 definePageMeta 中設定。

如果你在頁面元件中啟用了 <Transition>,請確保該頁面只有一個根元素。

由於 <NuxtPage> 在底層使用了 <Suspense>,因此在頁面更改期間,元件生命週期行為與典型的 Vue 應用程式不同。

在典型的 Vue 應用程式中,新的頁面元件僅在舊元件完全解除安裝 之後 才掛載。然而,在 Nuxt 中,由於 Vue <Suspense> 的實現方式,新的頁面元件在舊元件解除安裝 之前 就掛載了。

屬性

  • name:告訴 <RouterView> 渲染匹配路由記錄的 components 選項中具有相應名稱的元件。
    • 型別:string
  • route:已解析所有元件的路由位置。
    • 型別:RouteLocationNormalized
  • pageKey:控制 NuxtPage 元件何時重新渲染。
    • 型別:stringfunction
  • transition:為所有使用 NuxtPage 元件渲染的頁面定義全域性過渡。
  • keepalive:控制使用 NuxtPage 元件渲染的頁面狀態保持。
Nuxt 透過掃描並渲染 /pages 目錄中找到的所有 Vue 元件檔案,自動解析 nameroute

示例

例如,如果你傳遞一個從不更改的鍵,<NuxtPage> 元件將只渲染一次——在它首次掛載時。

app/app.vue
<template>
  <NuxtPage page-key="static" />
</template>

你還可以使用基於當前路由的動態鍵

<NuxtPage :page-key="route => route.fullPath" />
不要在這裡使用 $route 物件,因為它可能會導致 <NuxtPage> 使用 <Suspense> 渲染頁面時出現問題。

或者,pageKey 可以透過 definePageMeta/pages 目錄中 Vue 元件的 <script> 部分作為 key 值傳遞。

app/pages/my-page.vue
<script setup lang="ts">
definePageMeta({
  key: route => route.fullPath,
})
</script>
Docs > 4 X > Examples > Routing > Pages 中閱讀並編輯即時示例。

頁面引用

要獲取頁面元件的 ref,請透過 ref.value.pageRef 訪問它

app/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/app.vue
<template>
  <NuxtPage :foobar="123" />
</template>

我們可以在頁面元件中訪問 foobar 屬性

app/pages/page.vue
<script setup lang="ts">
const props = defineProps<{ foobar: number }>()

console.log(props.foobar) // Outputs: 123

如果你沒有使用 defineProps 定義屬性,任何傳遞給 NuxtPage 的屬性仍然可以直接從頁面 attrs 中訪問

app/pages/page.vue
<script setup lang="ts">
const attrs = useAttrs()
console.log(attrs.foobar) // Outputs: 123
</script>
瞭解更多請參閱 文件 > 4 X > 指南 > 目錄結構 > App > 頁面