error.vue

error.vue 文件是 Nuxt 应用程序中的错误页面。

在应用程序的生命周期中,某些错误可能会在运行时意外出现。在这种情况下,我们可以使用 error.vue 文件来覆盖默认错误文件并很好地显示错误。

error.vue
<script setup lang="ts">
import type { NuxtError } from '#app'

const props = defineProps<{ error: NuxtError }>()
</script>

<template>
  <div>
    <h1>{{ error.status }}</h1>
    <NuxtLink to="/">Go back home</NuxtLink>
  </div>
</template>
虽然它被称为"错误页面",但它不是路由,不应放在你的 ~/pages 目录中。出于同样的原因,你不应在此页面中使用 definePageMeta。话虽如此,你仍然可以通过利用 NuxtLayout 组件并指定布局的名称来在错误文件中使用布局。

错误页面有一个 prop - error,其中包含一个错误供你处理。

error 对象提供以下字段:

interface NuxtError {
  status: number
  fatal: boolean
  unhandled: boolean
  statusText?: string
  data?: unknown
  cause?: unknown
  // `status` 的遗留/弃用等效项
  statusCode: number
  // `statusText` 的遗留/弃用等效项
  statusMessage?: string
}

如果你有带有自定义字段的错误,它们将丢失;你应该改为将它们分配给 data

throw createError({
  status: 404,
  statusText: 'Page Not Found',
  data: {
    myCustomField: true,
  },
})