nuxt logo

文档翻译(非官方)

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="/">返回首页</NuxtLink>
  </div>
</template>

尽管它被称为“错误页面”,但它不是一个路由,不应放置在 ~/pages 目录中。出于同样的原因,不应在此页面中使用 definePageMeta。话虽如此,您仍然可以通过使用 NuxtLayout 组件并指定布局名称,在错误文件中使用布局。

错误页面有一个单一的 prop - error,其中包含您需要处理的错误。

error 对象提供以下字段:

{
  statusCode: number
  fatal: boolean
  unhandled: boolean
  statusMessage?: string
  data?: unknown
  cause?: unknown
}

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

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