error.vue
error.vue 檔案是 Nuxt 應用程式中的錯誤頁面。
在應用程式的生命週期中,一些錯誤可能會在執行時意外出現。在這種情況下,我們可以使用 error.vue
檔案來覆蓋預設的錯誤檔案,並優雅地顯示錯誤。
error.vue
<script setup lang="ts">
import type { NuxtError } from '#app'
const props = defineProps({
error: Object as () => NuxtError,
})
</script>
<template>
<div>
<h1>{{ error.statusCode }}</h1>
<NuxtLink to="/">Go back home</NuxtLink>
</div>
</template>
儘管它被稱為“錯誤頁面”,但它不是路由,不應放置在您的
~/pages
目錄中。出於同樣的原因,您不應在此頁面中使用 definePageMeta
。話雖如此,您仍然可以透過使用 NuxtLayout
元件並指定佈局名稱,在錯誤檔案中使用佈局。錯誤頁面只有一個 prop——error
,其中包含您需要處理的錯誤。
error
物件提供以下欄位
interface NuxtError {
statusCode: number
fatal: boolean
unhandled: boolean
statusMessage?: string
data?: unknown
cause?: unknown
}
如果您有自定義欄位的錯誤,它們將會丟失;您應該將它們分配給 data
throw createError({
statusCode: 404,
statusMessage: 'Page Not Found',
data: {
myCustomField: true,
},
})